If you're working with Laravel and want to make your application faster and more efficient, you're in the right place! I’m going to walk you through some simple steps that will help optimize your Laravel app.
These tips focus on improving performance, reducing load times, and making your app run smoother. Whether you’re dealing with a large number of users or trying to speed up your database queries, these methods will help you achieve better performance.
Optimizing and increasing the speed of Laravel
Caching is crucial for improving the speed of frequently accessed data.
// Store data in the cache
Cache::put('key', $data, now()->addMinutes(10));
// Retrieve data from the cache
$data = Cache::remember('key', 10, function () {
return DB::table('users')->get();
});
Avoid N+1 query problems by eager loading relationships.
// Without eager loading (N+1 issue)
$users = User::all();
foreach ($users as $user) {
echo $user->posts->count();
}
// With eager loading
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count();
}
The query builder is often faster for complex queries.
$users = DB::table('users')
->join('posts', 'users.id', '=', 'posts.user_id')
->where('users.active', 1)
->select('users.name', DB::raw('COUNT(posts.id) as post_count'))
->groupBy('users.id')
->get();
Ensure frequently queried columns are indexed.
CREATE INDEX users_active_index ON users(active);
In Laravel migration:
$table->index('active');
Offload tasks like email sending or data processing to queues.
dispatch(new SendEmailJob($user));
Run heavy operations only when necessary by limiting middleware.
// Apply middleware only to specific routes
Route::middleware(['auth', 'throttle:60,1'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});
Use tools like Laravel Mix to minify CSS and JavaScript.
npm run prod
In webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.version();
Load only what’s needed for display.
$users = User::paginate(10);
php artisan config:cache
php artisan route:cache
Redis is faster than file or database storage for sessions and cache.
CACHE_DRIVER=redis
SESSION_DRIVER=redis
Use composer dump-autoload --optimize
to optimize the Composer autoloader.
Use persistent connections in the env file.
DB_CONNECTION=mysql
DB_PORT=3306
DB_PERSISTENT_CONNECTION=true
Disable unused middleware and service providers in config/app.php.
Transform large datasets efficiently.
return UserResource::collection(User::all());
Lazy collections reduce memory usage when processing large datasets.
DB::table('users')->lazy()->each(function ($user) {
// Process each user
});
Use compiled views and avoid unnecessary logic in templates.
// Avoid in Blade template
@if(count($users) > 0)
@else
@endif
// Instead, use
@forelse($users as $user)
{{ $user->name }}
@empty
No users found.
@endforelse
Offload static files like images, CSS, and JS to a CDN.
Always use the latest stable versions of Laravel and PHP for performance improvements.
If applicable, use connection pooling for database connections to reduce overhead.
Use tools like Laravel Telescope, Debugbar, or external monitoring tools like New Relic to identify bottlenecks.
composer require barryvdh/laravel-debugbar --dev
You might also like: