Most Laravel tutorials stop at hasMany and belongsTo. That's fine for prototypes, but enterprise applications demand more — query encapsulation, domain-driven data access, and performance characteristics you can reason about under load. After shipping production systems for clients ranging from logistics platforms to multi-tenant SaaS tools, here are the Eloquent patterns that actually survive contact with real-world complexity.
Repository Pattern Done Right (Without the Boilerplate Tax)
The repository pattern has a bad reputation in Laravel circles because most implementations wrap Eloquent so thinly they add zero value. The real goal isn't abstraction for abstraction's sake — it's query encapsulation and testability.
Instead of a generic UserRepository with fifty methods, build focused query objects:
<?php
namespace App\Queries;
use App\Models\Order;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
class PendingOrdersQuery
{
public function __construct(
private readonly int $merchantId,
private readonly ?string $search = null,
private readonly string $sortBy = 'created_at',
private readonly string $direction = 'desc',
) {}
public function paginate(int $perPage = 25): LengthAwarePaginator
{
return Order::query()
->whereMerchant($this->merchantId)
->pending()
->when($this->search, fn ($q) => $q->search($this->search))
->with(['customer', 'items.product'])
->orderBy($this->sortBy, $this->direction)
->paginate($perPage);
}
}
This is composable, injectable, and trivially unit-testable. The controller becomes a thin orchestrator, not a query builder.
Meaningful Local Scopes and Scope Chaining
Local scopes are underused beyond simple filters. The real power comes from treating them as a fluent vocabulary for your domain:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Subscription extends Model
{
public function scopeActive(Builder $query): Builder
{
return $query->where('status', 'active')
->where('ends_at', '>', now());
}
public function scopeExpiringWithin(Builder $query, int $days): Builder
{
return $query->active()
->whereBetween('ends_at', [now(), now()->addDays($days)]);
}
public function scopeForPlan(Builder $query, string $plan): Builder
{
return $query->whereHas('plan', fn ($q) => $q->where('slug', $plan));
}
}
Now your application code reads like business logic:
$atRisk = Subscription::expiringWithin(14)
->forPlan('pro')
->with('user')
->get();
Anyone reading that understands intent without digging through SQL.
Custom Casts for Domain Value Objects
Custom casts are one of the most underutilised features for enterprise projects. They let you replace primitive obsession with proper value objects — without changing your schema.
<?php
namespace App\Casts;
use App\ValueObjects\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class MoneyCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes): Money
{
return new Money(
amount: (int) $value,
currency: $attributes['currency'] ?? 'AED'
);
}
public function set($model, string $key, $value, array $attributes): array
{
if ($value instanceof Money) {
return [
$key => $value->amount,
'currency' => $value->currency,
];
}
return [$key => $value];
}
}
Apply it on the model:
protected $casts = [
'price' => MoneyCast::class,
'tax' => MoneyCast::class,
];
Now $product->price returns a Money object with formatting, arithmetic, and currency-awareness baked in — not a float that silently misbehaves.
Eager Loading Strategies That Don't Bite You
N+1 issues in enterprise apps often appear not in loops, but in conditional relationships — you eager load a relation that's only needed in one code path, dragging memory up for every request.
Use lazy eager loading with guards for conditional cases:
// In a service, only load invoices when generating reports
public function prepareExport(Collection $orders): Collection
{
if ($this->includeInvoices) {
$orders->load('invoices.lineItems');
}
return $orders->map(fn ($order) => $this->transform($order));
}
For API resources that vary by context, conditional relationship loading via request parameters keeps payloads lean:
// OrderController
$query = Order::query()->forMerchant($merchantId);
if ($request->boolean('with_customer')) {
$query->with('customer');
}
if ($request->boolean('with_items')) {
$query->with('items.product');
}
This pattern — common in projects built at a professional web agency where client APIs serve multiple consumers — prevents over-fetching without maintaining multiple endpoint versions.
Model Observers vs. Event Listeners: Choose Deliberately
Observers feel convenient but couple your side effects tightly to model lifecycle events. For simple auditing or cache-busting, they're fine. For anything involving queued jobs, external APIs, or multi-step workflows, domain events with dedicated listeners give you far more control:
<?php
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Jobs\SendOrderConfirmation;
use App\Jobs\UpdateInventory;
use App\Jobs\NotifyWarehouse;
class HandleOrderPlaced
{
public function handle(OrderPlaced $event): void
{
SendOrderConfirmation::dispatch($event->order)->onQueue('notifications');
UpdateInventory::dispatch($event->order)->onQueue('sync');
NotifyWarehouse::dispatch($event->order)->onQueue('integrations');
}
}
This approach makes your side effects visible, testable, and independently deployable. Observers that dispatch jobs can silently fail in ways that are painful to debug in production.
Global Scopes for Multi-Tenancy (Without the Footguns)
Global scopes power the multi-tenancy layer in almost every serious SaaS built on Laravel. The footgun is forgetting to remove them when you need system-level queries:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model): void
{
if ($tenantId = app('currentTenant')?->id) {
$builder->where('tenant_id', $tenantId);
}
}
}
Always document that withoutGlobalScope(TenantScope::class) exists and when to use it — typically in console commands, background jobs, and cross-tenant admin queries. Build a SystemContext wrapper to make this explicit rather than leaving developers to remember the method name:
class SystemContext
{
public static function query(string $model): Builder
{
return $model::withoutGlobalScope(TenantScope::class);
}
}
// Usage in a console command
$allExpired = SystemContext::query(Subscription::class)
->where('ends_at', '<', now())
->get();
Conclusion
Eloquent's surface area is deceptively large. The patterns that separate maintainable enterprise codebases from fragile ones aren't exotic — they're disciplined applications of what the framework already provides. Query objects beat fat repositories. Meaningful scopes replace magic strings. Custom casts eliminate primitive obsession. And explicit event listeners outlast observer magic every time the requirements change.
The consistent thread: make intent readable and side effects visible. Code you can read under pressure is code you can fix under pressure. Pick the patterns that match your domain complexity, and resist the urge to add abstraction layers just because a blog post said to.
Top comments (0)