Kritim Yantra
Mar 24, 2025
Laravel is one of the most popular PHP frameworks, known for its elegant syntax and developer-friendly features. However, as your application grows, performance can become a concern. In this guide, we'll explore practical ways to optimize your Laravel 12 applications, making them faster and more efficient.
Before diving into optimization techniques, let's understand why performance is crucial:
One of the simplest yet most effective optimizations in Laravel is route caching.
php artisan route:cache
This command compiles all your route registrations into a single file for faster loading. Remember to run this after any route changes:
php artisan route:clear
Similarly, you can cache your configuration files:
php artisan config:cache
This combines all configuration files into a single file. Clear it when you make changes:
php artisan config:clear
Composer's autoloader can be optimized for production:
composer install --optimize-autoloader --no-dev
This creates a class map for faster autoloading and skips development dependencies.
A common performance issue is the N+1 query problem. Consider this example:
// Inefficient way (N+1 queries)
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
// Optimized with eager loading (2 queries)
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name;
}
Add indexes to columns you frequently search or join on:
Schema::table('users', function (Blueprint $table) {
$table->index('email');
});
Use Laravel's query builder methods wisely:
// Instead of
User::where('active', 1)->get()->count();
// Use
User::where('active', 1)->count();
Laravel's cache system is powerful:
// Store data in cache for 60 minutes
$value = Cache::remember('users', 60, function () {
return DB::table('users')->get();
});
// Retrieve later
$users = Cache::get('users');
When dealing with large datasets, use lazy collections to reduce memory usage:
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$handle = fopen('large_file.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
})->chunk(4)->map(function ($lines) {
return processLines($lines);
})->each(function ($lines) {
// Process each chunk
});
Compile and cache your Blade views:
php artisan view:cache
Clear when needed:
php artisan view:clear
Avoid complex logic in views. Instead:
// In controller
return view('posts.index', [
'activePosts' => $this->postService->getActivePosts()
]);
// Instead of doing this in the view
@foreach(Post::where('active', 1)->get() as $post)
Offload time-consuming tasks to queues:
// Dispatch a job
ProcessPodcast::dispatch($podcast)->onQueue('processing');
// Run queue worker
php artisan queue:work --queue=processing
npm run build
Add cache headers in your .htaccess
(Apache) or server config:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
Enable PHP's OPcache in your php.ini
:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
Use Laravel Telescope (for local development) or Horizon (for production) to monitor performance:
composer require laravel/telescope
php artisan telescope:install
php artisan migrate
For production, use more efficient session drivers:
SESSION_DRIVER=redis
Or for file-based sessions:
SESSION_DRIVER=file
SESSION_LIFETIME=120
Update your composer.json
:
{
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/Helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
}
}
Then run:
composer dump-autoload -o
When deploying, run:
php artisan optimize
This combines route, config, and view caching into one command.
After implementing optimizations, test your application:
php artisan serve
with the --port
option to test locallyExample with Apache Bench:
ab -n 1000 -c 100 http://your-laravel-app.test/
Optimizing Laravel applications is an ongoing process. Start with the low-hanging fruit like route and
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google