Skip to content
Laravel Fanboy, home

Tips & snippets

Small things that make Laravel apps nicer to build and run. Every snippet links to the docs page it was checked against. Tips marked New in 13 need Laravel 13 or later.

Catch N+1 queries before production does

Throw an exception whenever a relationship is lazy loaded, but only outside production so a missed eager load never takes the site down.

Official docsLink to this tip

use Illuminate\Database\Eloquent\Model;

// app/Providers/AppServiceProvider.php
public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}

Fail loudly on unfillable attributes

By default, mass-assigning a field that isn't fillable is silently ignored. Turn that into an exception locally so typos surface immediately.

Official docsLink to this tip

Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());

Run independent queries at the same time

Concurrency::run executes closures in child PHP processes. Give the array keys and the results come back under the same keys.

Official docsLink to this tip

use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;

$results = Concurrency::run([
    'users' => fn () => DB::table('users')->count(),
    'orders' => fn () => DB::table('orders')->count(),
]);

$results['users']; // int

Do the slow bit after the response is sent

Concurrency::defer runs closures concurrently after the HTTP response has gone out. Ideal for metrics and pings whose results you don't need.

Official docsLink to this tip

use App\Services\Metrics;
use Illuminate\Support\Facades\Concurrency;

Concurrency::defer([
    fn () => Metrics::report('users'),
    fn () => Metrics::report('orders'),
]);

Route jobs to queues in one place

New in 13

Instead of calling onQueue() everywhere, declare which connection and queue a job class (or interface) should use from a service provider.

Official docsLink to this tip

use App\Jobs\ProcessPodcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Support\Facades\Queue;

public function boot(): void
{
    Queue::route(ProcessPodcast::class, connection: 'redis', queue: 'podcasts');
    Queue::route(ShouldBroadcast::class, queue: 'events');
}

Configure jobs with attributes

New in 13

Retries, timeouts and exception limits can live right on the class as PHP attributes.

Official docsLink to this tip

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;

#[Tries(25)]
#[MaxExceptions(3)]
#[Timeout(120)]
class ProcessPodcast implements ShouldQueue
{
    use Queueable;
}

Extend a cache item without re-storing it

New in 13

Cache::touch pushes out an item's expiry without fetching and re-writing the value. Handy for sliding expirations.

Official docsLink to this tip

use Illuminate\Support\Facades\Cache;

// Keep the cached report alive for another hour
Cache::touch('reports.monthly', 3600);

Semantic search from the query builder

New in 13

On PostgreSQL with pgvector (or MariaDB 11.7+), whereVectorSimilarTo filters and orders rows by cosine similarity. Pass a plain string and Laravel generates the embedding through the Laravel AI SDK, so that needs to be configured.

Official docsLink to this tip

$documents = DB::table('documents')
    ->whereVectorSimilarTo('embedding', 'Best wineries in Napa Valley')
    ->limit(10)
    ->get();

Middleware and authorization on the controller

New in 13

Declare middleware and policy checks next to the methods they protect.

Official docsLink to this tip

use Illuminate\Routing\Attributes\Controllers\Authorize;
use Illuminate\Routing\Attributes\Controllers\Middleware;

#[Middleware('auth')]
class CommentController
{
    #[Middleware('subscribed')]
    #[Authorize('create', [Comment::class, 'post'])]
    public function store(Post $post)
    {
        // ...
    }
}

Find your slowest tests

The --profile flag lists the slowest tests right in the CLI output.

Official docsLink to this tip

php artisan test --profile

Publish only the config file you need

New apps ship with a slim config directory. Publish a single framework config file when you need to change it.

Official docsLink to this tip

php artisan config:publish concurrency

Prefer Arr::first over global array_first()

Laravel 13 pulls in a PHP 8.5 polyfill whose array_first() takes no callback. Use the Arr helper when you need to match a condition.

Official docsLink to this tip

use Illuminate\Support\Arr;

$firstAdmin = Arr::first($users, fn ($user) => $user['is_admin']);