Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 67 ยท Caching and Performance

Performance and Optimization in Laravel

Make a Laravel app fast - optimize commands, config and route caches, query counts and indexes, queues for slow work, OPcache, Octane, Telescope and Debugbar.

A default Laravel app is fast enough for most projects, and the framework does a lot to help. But "fast enough" ends when a page runs 200 queries, when a request sends an email before answering, or when the server re-reads every config file on every request. Performance work in Laravel follows a simple order: measure first, fix the biggest cost, measure again.

This lesson gives you a practical checklist. You will see the artisan commands that cache the framework's own bootstrapping, learn how to count and reduce database queries, see why slow work belongs on a queue, and get an overview of OPcache, Octane and the debugging tools. Real Laravel code is read-only here; the runnable examples count queries and compare query plans with plain PHP and SQLite. If you want the language-level view, see PHP performance, and for storing results see caching.

Where time goes

flowchart LR
    R["Request"] --> B["Framework boot<br/>(config, routes, providers)"]
    B --> M["Middleware and controller"]
    M --> D[("Database queries")]
    M --> X["Slow work<br/>(mail, API calls, images)"]
    M --> V["View rendering"]
    V --> S["Response"]

Most slow pages are slow in one of three places: too many queries, slow work done inside the request, or an uncached boot.

Cache the framework's own work

On every request Laravel normally reads all config files, builds the route table, and finds your Blade views. In production you can compile that work once:

Terminal
php artisan config:cache     # merge all config files into one cached file
php artisan route:cache      # compile the route table
php artisan view:cache       # precompile every Blade template
php artisan event:cache      # cache the discovered event listeners

php artisan optimize         # runs the caches above in one command
php artisan optimize:clear   # removes them again

Run php artisan optimize as part of every deployment (see deploying Laravel). Two rules keep this safe:

  • After config:cache, the .env file is no longer read, so env() returns null anywhere outside config/ files. Read environment values only inside config files and use config('app.name') everywhere else (configuration and environments).
  • route:cache needs every route to be a controller action or an invokable class. Closure routes cannot be cached in all setups, so use controllers for anything that ships.

Do not run these caches on your local machine while developing, or your edits to config and routes will seem to have no effect. If that happens, run php artisan optimize:clear.

Count your queries

The most common Laravel performance problem is the N+1 query: one query to load a list, then one more query per row to load a relation. Ten posts become eleven queries, a thousand posts become 1,001. The fix is eager loading with with() (eager loading and N+1).

PHP
// 1 query for posts + 1 query per post for the author
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name;
}

// 2 queries in total
$posts = Post::with('author')->get();

Make Laravel shout about it during development. In AppServiceProvider::boot():

PHP
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

Model::preventLazyLoading(! app()->isProduction());   // exception on lazy loading in dev
Model::shouldBeStrict(! app()->isProduction());       // also guards missing attributes, mass assignment

DB::listen(function ($query) {
    if ($query->time > 100) {                          // milliseconds
        logger()->warning('Slow query', ['sql' => $query->sql, 'ms' => $query->time]);
    }
});

DB::listen receives every query with its SQL, bindings and time. That is how Telescope and Debugbar work, and the same idea is behind the counter below.

PHP Counting queries: lazy loading vs eager loading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The number of queries for eager loading stays at two no matter how many posts you load. That constant cost is the whole point.

Add the right indexes

A query that filters or sorts on an unindexed column makes the database read the whole table. Add an index for the columns you use in where, orderBy and joins, in a migration (migrations):

PHP
Schema::table('posts', function (Blueprint $table) {
    $table->index('user_id');                      // foreign keys: foreignId()->constrained() adds one for you
    $table->index(['status', 'published_at']);     // composite: filter by status, sort by date
});

Check a query with ->toSql() or ->explain() on the builder. The stand-in below compares what SQLite reports for the same query before and after an index exists.

PHP A query plan before and after an index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A SCAN reads every row; a SEARCH ... USING INDEX jumps straight to the matches. Indexes are not free: each one slows writes slightly and uses disk space, so index what you query, not every column.

More query habits

  • Select only what you need: Post::select('id', 'title')->get() moves less data than Post::all().
  • Paginate instead of loading thousands of rows, and use cursorPaginate() or chunkById() for very large sets (querying with Eloquent).
  • Use withCount() instead of loading a relation just to count it.
  • Cache expensive results with Cache::remember() and clear them on write.

Move slow work to a queue

A user should not wait while you send an email, resize an image or call a slow API. Dispatch a job and answer immediately; a worker does the work in the background (queues and jobs).

PHP
public function store(StoreOrderRequest $request)
{
    $order = Order::create($request->validated());

    SendOrderConfirmation::dispatch($order);   // returns at once, runs in a worker

    return redirect()->route('orders.show', $order);
}

The response time is now the time to insert a row, not the time to talk to a mail server.

Make PHP itself faster

OPcache stores compiled PHP bytecode in memory so files are not parsed on every request. It ships with PHP and should be enabled in production. For the fastest setup, set opcache.validate_timestamps=0 and reload PHP-FPM on every deploy so the new code is picked up.

Laravel Octane boots your application once and keeps it in memory between requests, served by FrankenPHP, Swoole or RoadRunner. It removes the boot cost and can multiply throughput, but it changes the rules: the app is a long-running process, so static properties, singletons and any state you store on them survive across requests. Never keep per-user data in a singleton. Try Octane after the cheaper fixes above, and test your app under it.

Also worth knowing: use Redis for cache, sessions and queues instead of the database or files on busy sites, run composer install --optimize-autoloader --no-dev in production, and serve static assets from a CDN with cache headers.

Tools for finding problems

Tool What it shows Where to use it
Laravel Debugbar Queries, timings, views, memory in a toolbar Local development
Laravel Telescope Requests, queries, jobs, exceptions, mail, cache Local and staging (heavy for production)
Laravel Pulse Slow requests, slow queries, queue health, usage Production dashboard
DB::listen and logs Slow query log you control Anywhere
Database slow query log, EXPLAIN What the database really does Anywhere

Debugbar and Telescope add overhead and expose internals, so never enable them on a public production site without protecting access.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does php artisan optimize do?

    optimize runs the framework caches (config, events, routes, views) so they are compiled once instead of on every request.
  2. 2. After php artisan config:cache, why does env('APP_NAME') return null in a controller?

    Once the config is cached, Laravel stops reading .env. Read env() only in config files and use config() everywhere else.
  3. 3. A page lists 50 posts and shows each author, producing 51 queries. What is this called and how do you fix it?

    One query for the list plus one per row is the N+1 problem. Eager loading brings it down to two queries.
  4. 4. What is the main risk of running an app under Octane?

    Octane keeps the booted application in memory between requests, so any per-request state stored globally can leak into the next request.
  5. 5. Why should sending a confirmation email usually be a queued job?

    Slow external work inside the request makes users wait. A queued job lets the response return immediately while a worker sends the mail.

Summary

  • Measure before optimizing: Debugbar, Telescope, Pulse, DB::listen and EXPLAIN show what is slow.
  • Run php artisan optimize on deploy; use env() only inside config files.
  • Fix N+1 queries with eager loading and turn on preventLazyLoading in development.
  • Index the columns you filter, sort and join on.
  • Move slow work to queues and cache expensive results.
  • Enable OPcache, consider Redis and Octane, and be careful with long-lived state.

Next: Building JSON APIs with API Resources