Eloquent ORM is one of Laravel's standout features, but improper use can lead to performance bottlenecks. Use eager loading (with
) to reduce the number of queries executed.
// Instead of $users = User::all(); foreach ($users as $user) { echo $user->profile->bio;
} // Use eager loading $users = User::with('profile')->get(); foreach ($users as $user) { echo $user->profile->bio;
}
The N+1 query problem occurs when an application executes a query for each record in a collection. Eager loading helps to mitigate this.
$posts = Post::with('comments')->get();
Ensure your database tables are properly indexed. Index columns that are frequently used in WHERE
, JOIN
, and ORDER BY
clauses.
Leverage Laravel's built-in caching mechanisms to store frequently accessed data.
$users = Cache::remember('users', 60, function () { return User::all();
});
Choose the appropriate cache driver for your environment. For production, consider using redis
or memcached
instead of the default file
cache.
CACHE_DRIVER=redis
Minify your CSS and JavaScript files to reduce their size and improve load times.
npm run production
Host your assets on a CDN to reduce latency and speed up asset delivery.
<link rel="stylesheet" href="https://cdn.example.com/css/app.css">
Use modern image formats like WebP for better compression and faster loading times.
Use image compression tools to reduce the size of your images without sacrificing quality.
composer require spatie/laravel-image-optimizer
Laravel automatically caches compiled Blade templates, but you can clear and regenerate the cache if necessary.
php artisan view:cache
Keep your Blade templates clean by moving complex logic to controllers or view composers.
Use Laravel queues to handle time-consuming tasks like sending emails or processing uploads.
dispatch(new SendEmailJob($user));
Ensure you have configured enough queue workers to handle the job load efficiently.
php artisan queue:work --daemon
Configure persistent database connections to reduce the overhead of establishing a new connection for each request.
'options' => [PDO::ATTR_PERSISTENT => true],
OPcache can significantly improve PHP performance by storing precompiled script bytecode in memory.
opcache.enable=1 opcache.memory_consumption=128 opcache.max_accelerated_files=10000
Cache your configuration files to avoid parsing them on each request.
php artisan config:cache
Cache your routes for faster route registration.
php artisan route:cache
Laravel Debugbar is a great tool for profiling your application and identifying performance bottlenecks.
composer require barryvdh/laravel-debugbar --dev
Consider using monitoring tools like Blackfire, New Relic, or Laravel Telescope to gain insights into your application's performance.