5 min. de lectura (aproximado)

Tutorial Laravel 13 para expertos

Este tutorial está pensado para desarrolladores que ya dominan el framework, rutas, middleware,Eloquent básico, queues, Service Container, Form Requests, Policies, etc. En este tutotial se muestran técnicas que realmente marcan la diferencia en aplicaciones de producción con alto tráfico, lógica de negocio compleja y requisitos de rendimiento.

Eloquent avanzado

Composición de Query Scopes + withWhereHas

// app/Models/Order.php
public function scopePaid(Builder $query): Builder
{
    return $query->where('status', 'paid');
}

public function scopeOfCustomer(Builder $query, int $customerId): Builder
{
    return $query->where('customer_id', $customerId);
}

public function scopeWithRecentPayments(Builder $query, int $days = 30): Builder
{
    return $query->withWhereHas('payments', function ($q) use ($days) {
        $q->where('created_at', '>=', now()->subDays($days));
    });
}

// Uso limpio
$orders = Order::paid()
    ->ofCustomer($customerId)
    ->withRecentPayments(15)
    ->with(['items.product'])
    ->latest()
    ->get();
"withWhereHas" evita el problema N+1 y filtra en la misma consulta. Combinarlo con scopes para queries legibles y reutilizables.

Subqueries

$users = User::query()
    ->select('users.*')
    ->selectSub(
        Order::selectRaw('COUNT(*)')
            ->whereColumn('orders.user_id', 'users.id')
            ->where('status', 'paid'),
        'paid_orders_count'
    )
    ->selectSub(
        Order::selectRaw('SUM(total)')
            ->whereColumn('orders.user_id', 'users.id')
            ->where('status', 'paid'),
        'lifetime_value'
    )
    ->having('lifetime_value', '>', 1000)
    ->get();
Ideal para dashboards y rankings sin cargar colecciones innecesarias.

Custom Casts y Value Objects

// app/Casts/MoneyCast.php
class MoneyCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes): Money
    {
        return new Money($value, $attributes['currency'] ?? 'EUR');
    }

    public function set($model, string $key, $value, array $attributes): array
    {
        return [
            'amount' => $value instanceof Money ? $value->amount : $value,
            'currency' => $value instanceof Money ? $value->currency : 'EUR',
        ];
    }
}

// En el modelo
protected function casts(): array
{
    return [
        'price' => MoneyCast::class,
        'settings' => AsArrayObject::class, // o tu propio cast más sofisticado
    ];
}
Usat Value Objects reales. Evitar trabajar con enteros sueltos o arrays mágicos.

Custom Collections y Macros

// app/Collections/OrderCollection.php
class OrderCollection extends Collection
{
    public function totalRevenue(): Money
    {
        return $this->sum(fn (Order $order) => $order->total);
    }

    public function groupByStatus(): Collection
    {
        return $this->groupBy('status');
    }
}

// En el modelo
public function newCollection(array $models = []): OrderCollection
{
    return new OrderCollection($models);
}

Caching que no te muerde después

Cache con tags y versionado de claves

$version = Cache::get('orders:version', 1);

$orders = Cache::tags(['orders', "customer:{$customerId}"])
    ->remember("orders:customer:{$customerId}:v{$version}", 3600, function () use ($customerId) {
        return Order::ofCustomer($customerId)->with('items')->get();
    });

// Invalidación limpia
Cache::tags(['orders'])->flush();
// o solo de un cliente
Cache::tags(["customer:{$customerId}"])->flush();

// Al crear/actualizar un pedido
Cache::increment('orders:version');

Cache Locks

$lock = Cache::lock('recalculate-stats:'.$userId, 10);

if ($lock->get()) {
    try {
        // Cálculo costoso
        $stats = $this->heavyCalculation($userId);
        Cache::put("stats:{$userId}", $stats, 3600);
    } finally {
        $lock->release();
    }
} else {
    // Esperar o devolver valor antiguo
    return Cache::get("stats:{$userId}");
}

Orquestación avanzada de Jobs

Batching + Chaining + afterCommit

use Illuminate\Support\Facades\Bus;

$batch = Bus::batch([
    new ProcessOrderItems($order),
    new GenerateInvoice($order),
    new NotifyWarehouse($order),
])
->then(function (Batch $batch) {
    // Todo terminó bien
    event(new OrderFullyProcessed($batch->id));
})
->catch(function (Batch $batch, Throwable $e) {
    // Falló alguno
    Log::error('Batch falló', ['batch' => $batch->id, 'error' => $e->getMessage()]);
})
->finally(function (Batch $batch) {
    // Siempre se ejecuta
})
->name('Order Processing #'.$order->id)
->allowFailures()
->dispatch();
Para jobs que deben ejecutarse después de que la transacción se confirme:
ProcessPayment::dispatch($payment)->afterCommit();

Job Middleware y Rate Limiting personalizado

// app/Jobs/Middleware/RateLimited.php
class RateLimited
{
    public function handle(object $job, Closure $next): void
    {
        Redis::throttle('process-payments')
            ->allow(100)
            ->every(60)
            ->then(function () use ($job, $next) {
                $next($job);
            }, function () use ($job) {
                $job->release(30); // reintentar en 30s
            });
    }
}

// En el Job
public function middleware(): array
{
    return [new RateLimited];
}

Service Container

// Contextual binding
$this->app->when(ReportController::class)
    ->needs(ExportService::class)
    ->give(fn () => new CsvExportService());

$this->app->when(AdminReportController::class)
    ->needs(ExportService::class)
    ->give(fn () => new PdfExportService());

// Tagging + resolución
$this->app->tag([
    SlackNotifier::class,
    EmailNotifier::class,
    SmsNotifier::class,
], 'notifiers');

$notifiers = $this->app->tagged('notifiers');

Checklist de rendimiento para producción

  • Eager loading agresivo + withCount / withSum / withExists.
  • Índices compuestos bien pensados (usa EXPLAIN).
  • chunkById() o lazy() / cursor() para datasets grandes.
  • Redis para cache, sessions y queues.
  • Octane (FrankenPHP o Swoole) cuando el bottleneck sea el bootstrap.
  • php artisan optimize + OPcache + config/route/view cache.
  • Telescope / Nightwatch / Pulsar solo en staging o con sampling.