Why Your Laravel App Is Slow
Introduction
Your Laravel app was fast on day one. The tables were small and every page rendered before you could notice. Then the data grew, and the same endpoints got slow while the code around them did not change.
It is almost never the framework. In the projects I've worked on it is the same six habits, repeated across the codebase: several writes for one use case, $with declared on the model, queries hiding inside accessors, reports built in Eloquent, SELECT * on every list, and a whole table loaded into PHP to be filtered there. Most are invisible at the call site, which is why they survive code review.
Here is each habit, what it looks like in the query log, and the fix. If you want the six applied one after another to a single codebase, Laravel Best Practices: Writing Laravel That Lasts does that in its Queries and Data Access chapter.
1. Several writes for one use case
A user subscribes. The controller creates the subscription and updates the user. An observer fires on created and saves the subscription again to set its status. One use case, three writes, and two files that each know part of what a finished subscription looks like.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Events\UserSubscribed;
use App\Http\Requests\SubscribeRequest;
use App\Models\Subscription;
use Illuminate\Http\JsonResponse;
class SubscribeController extends Controller
{
public function store(SubscribeRequest $request): JsonResponse
{
$subscription = Subscription::create($request->validated());
$subscription->user->update(['last_subscribed_at' => now()]);
event(new UserSubscribed($subscription));
return new JsonResponse($subscription, 201);
}
}<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\Subscription;
class SubscriptionObserver
{
public function created(Subscription $subscription): void
{
$subscription->status = 'active';
$subscription->save();
}
}Each statement runs on its own connection call and commits before the next one starts, so the database sees an insert, an update, and a second update where one insert and one update in a transaction carried all the information. The observer's save runs from inside Subscription::create(), because Eloquent fires created during save(), so by the time the controller reaches its second line the row has already been written twice. If the observer's save fails, the subscription exists with no status. If the user update fails, the user's timestamp disagrees with the subscription. Nobody reading the controller can tell what the finished row looks like, because the status comes from a file they have not opened.
Set every field the use case knows before the first insert, and put the two writes that must agree inside one transaction. The fix lives in a class of its own: a handler that takes a command object holding the fields, so the controller, a queued job, and a console command can all run it.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
final readonly class SubscribeCommand
{
public function __construct(
public int $userId,
public int $planId,
) {
}
}<?php
declare(strict_types=1);
namespace App\Models;
enum SubscriptionStatus: string
{
case ACTIVE = 'active';
case CANCELLED = 'cancelled';
}<?php
declare(strict_types=1);
namespace App\Subscriptions;
use App\Events\UserSubscribed;
use App\Models\Subscription;
use App\Models\SubscriptionStatus;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionInterface;
final readonly class SubscribeCommandHandler
{
public function __construct(
private ConnectionInterface $connection,
private Dispatcher $events,
) {
}
public function handle(SubscribeCommand $command): Subscription
{
$now = CarbonImmutable::now();
$subscription = $this->connection->transaction(function () use ($command, $now): Subscription {
$subscription = Subscription::query()->create([
'user_id' => $command->userId,
'plan_id' => $command->planId,
'status' => SubscriptionStatus::ACTIVE,
'started_at' => $now,
]);
User::query()
->whereKey($command->userId)
->update(['last_subscribed_at' => $now]);
return $subscription;
});
$this->events->dispatch(new UserSubscribed($subscription));
return $subscription;
}
}The observer is deleted. The event is dispatched after the transaction commits, so a listener never sees a subscription that is about to be rolled back. The app calls Model::unguard() in AppServiceProvider, the way Writing Laravel That Lasts does when it moves the reservations into a module, so the models declare no $fillable.
The course walks this fix through a reservation flow in Laravel Observers: Saving the Same Reservation Four Times.
2. Eager loading on the model
Someone added protected $with = ['profile', 'subscriptions'] to the User model because a dashboard needed both relations. Now every query that returns User models loads them, and the most frequent one is the one nobody wrote: the auth guard's lookup of the logged-in user on every authenticated request.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $with = ['profile', 'subscriptions'];
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
public function subscriptions(): HasMany
{
return $this->hasMany(Subscription::class);
}
}Open the query log on any page behind auth middleware and the first three queries are the same every time:
select * from `users` where `id` = ? limit 1
select * from `profiles` where `profiles`.`user_id` in (42)
select * from `subscriptions` where `subscriptions`.`user_id` in (42)The guard asked for one row. It got three queries, and the page that triggered them may never touch a profile or a subscription.
$with is applied inside the Eloquent builder's get(): the builder runs the main query, hydrates the rows into models, and then calls eagerLoadRelations() on them. So every call that returns models pays: get(), first(), find(), findOrFail(), all(), paginate(), and each batch of chunk(). Aggregates do not pay. count(), exists(), and sum() are passed through to the plain query builder underneath (toBase()), no models are hydrated, and there is nothing to eager load. The cost lands on the reads that return models, which is most of the reads a page runs.
Remove the line and load relations where they are used, because that is the only place that knows whether they are needed.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
public function subscriptions(): HasMany
{
return $this->hasMany(Subscription::class);
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __invoke(Request $request): View
{
$user = $request->user()->load(['profile', 'subscriptions']);
return view('dashboard', ['user' => $user]);
}
}The dashboard adds two queries and says so in its own method. The auth lookup runs one.
Lesson Laravel Eager Loading From the Model shows the same fix on a reservation detail page.
3. Queries hiding inside accessors
This is the N+1 (one query for the list, then one more for each row) that gets past code review, because the query is not in the controller. It is in an accessor on the model.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
{
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
protected function approvedCommentCount(): Attribute
{
return Attribute::make(
get: fn (): int => $this->comments()->where('approved', true)->count(),
);
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\View\View;
class ListPostsController extends Controller
{
public function __invoke(): View
{
$posts = Post::query()->latest()->take(50)->get();
return view('posts.index', ['posts' => $posts]);
}
}The Blade template renders {{ $post->approved_comment_count }} for each post. Fifty posts, fifty select count(*) queries, all firing after the controller has returned. Model::preventLazyLoading() does not catch this: it guards access to a relation as a property, and the accessor calls the relation as a method and runs its own query, which is not a lazy load as far as Eloquent is concerned.
Ask the database for the count in the same query, and keep accessors for transforming data that is already in memory.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
{
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\View\View;
class ListPostsController extends Controller
{
public function __invoke(): View
{
$posts = Post::query()
->withCount([
'comments as approved_comment_count' => fn (Builder $query) => $query->where('approved', true),
])
->latest()
->take(50)
->get();
return view('posts.index', ['posts' => $posts]);
}
}withCount() adds a subselect column, so the template reads the same $post->approved_comment_count and the page runs one query.
Lesson Laravel Accessors That Run Queries replaces one with withSum().
4. Eloquent for reporting queries
Eloquent is good at Subscription::query()->findOrFail($id). It is a poor fit for a report that joins several tables and aggregates across them, and the usual attempt looks like this:
<?php
declare(strict_types=1);
namespace App\Reports;
use App\Models\Plan;
final readonly class PlanRevenueReport
{
public function rows(): array
{
return Plan::query()
->with(['subscriptions.invoices'])
->get()
->map(function (Plan $plan): array {
$subscriptions = $plan->subscriptions;
return [
'plan' => $plan->name,
'revenue_cents' => $subscriptions->flatMap->invoices->where('paid', true)->sum('amount_cents'),
'trial_conversion' => $subscriptions->where('trial_converted', true)->count()
/ max($subscriptions->where('was_trial', true)->count(), 1),
];
})
->all();
}
}This loads every subscription and every invoice into memory as model objects, then does the arithmetic in PHP. The memory and the time grow with the size of the tables, not with the size of the report, which is a handful of rows.
Write the SQL you want, through the query builder, with the connection injected so the class is still testable.
<?php
declare(strict_types=1);
namespace App\Reports;
use Illuminate\Database\ConnectionInterface;
final readonly class PlanRevenueReport
{
public function __construct(
private ConnectionInterface $connection,
) {
}
public function rows(): array
{
// Sum paid invoices per subscription first, so a subscription with
// many invoices is still counted once in the trial columns.
$paidPerSubscription = $this->connection->table('invoices')
->select('subscription_id')
->selectRaw('SUM(amount_cents) as paid_cents')
->where('paid', true)
->groupBy('subscription_id');
$select = <<<'SQL'
p.name as plan,
COALESCE(SUM(i.paid_cents), 0) as revenue_cents,
SUM(CASE WHEN s.trial_converted THEN 1 ELSE 0 END) * 1.0
/ NULLIF(SUM(CASE WHEN s.was_trial THEN 1 ELSE 0 END), 0) as trial_conversion
SQL;
return $this->connection->table('plans as p')
->leftJoin('subscriptions as s', 's.plan_id', '=', 'p.id')
->leftJoinSub($paidPerSubscription, 'i', 'i.subscription_id', '=', 's.id')
->selectRaw($select)
->groupBy('p.id', 'p.name')
->get()
->all();
}
}You give up casts, accessors, and model events when you drop to the query builder. A report needs none of them. It needs one query that aggregates in the database, which returns one row per plan no matter how many invoices exist.
Lesson Laravel Query Builder for Reports, Not Eloquent Loops does this for an occupancy report.
5. SELECT * everywhere
User::query()->where('active', true)->get() pulls every column. The id, email, and name the page needed, plus the JSON preferences column, the biography text, stripe_metadata, and whatever else someone added to the table since.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
class ListActiveUsersController extends Controller
{
public function __invoke(): JsonResponse
{
$users = User::query()->where('active', true)->get();
return new JsonResponse($users->map(fn (User $user): array => [
'id' => $user->id,
'email' => $user->email,
'name' => $user->name,
]));
}
}Every byte of every unused column travels from the database to PHP, gets hydrated into a model attribute, and is thrown away by the map(). The cost is the widest columns on the table, and text and JSON columns tend to be the widest. It compounds with eager loading: a with('profile') on this query ships every profile's settings blob for a list that shows a name.
Select the columns the use case reads.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
class ListActiveUsersController extends Controller
{
public function __invoke(): JsonResponse
{
$users = User::query()
->where('active', true)
->select(['id', 'email', 'name'])
->get();
return new JsonResponse($users->map(fn (User $user): array => [
'id' => $user->id,
'email' => $user->email,
'name' => $user->name,
]));
}
}A relation you eager load needs its key in the select. Leave id out of a select() on the parent and with('profile') has nothing to match on.
Lesson Laravel Select and Pluck Instead of Every Column applies it to an arrivals list.
6. Loading the world into PHP
The habit that scales worst of the six:
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
class ListPowerUsersController extends Controller
{
public function __invoke(): JsonResponse
{
$powerUsers = User::all()
->filter(fn (User $user): bool => $user->subscriptions->where('status', 'active')->count() > 2)
->values();
return new JsonResponse($powerUsers);
}
}User::all() loads the entire table into memory. The closure then reads $user->subscriptions on each one, which lazy loads a subscription query per user. One PHP process holds every user in memory and runs one query per row to keep the few that qualify. The database could have answered with one query and an index.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\SubscriptionStatus;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
class ListPowerUsersController extends Controller
{
public function __invoke(): JsonResponse
{
$powerUsers = User::query()
->whereHas(
'subscriptions',
fn (Builder $query) => $query->where('status', SubscriptionStatus::ACTIVE),
'>',
2,
)
->get();
return new JsonResponse($powerUsers);
}
}whereHas() takes an operator and a count, so "more than two active subscriptions" becomes a correlated subquery and the filter runs where the index is. For anything more involved, write the join or subquery by hand and select the columns you need, as in section 4.
Lesson Laravel whereHas Instead of a Collection Filter covers the same fix on a guest list.
Where to start
Open the query log on your slowest page (Debugbar, Telescope, or DB::listen() in a service provider) and read the queries, not the timings. Four of these habits have a signature: the same select count(*) repeated once per row is an accessor; selects for tables the page never shows are $with; a select * from users with no where clause on a page that shows three users is a collection filter; one insert followed by updates to the same row is a use case writing itself in pieces. Fix the page with the most queries first.
Related Links
- Top 20 Mistakes Laravel Developers Makethe pillar index this deep dive sits under
- Laravel Best Practices: Writing Laravel That Laststhe course that applies these six fixes, one lesson each, to a single reservation system in its Queries and Data Access chapter
- Why Your Laravel Codebase Is Unmaintainablecontrollers calling controllers, hidden dependencies, traits holding business rules, and the default folder layout
- Stop Writing Laravel APIs Like Thismass assignment, untyped request values, one endpoint with many intents, and shared Form Requests
- Your Laravel Code Needs More Objectsarrays as data bags, Eloquent models passed through every layer, and primitives that should be value objects