Optimize Laravel 12 for Maximum Performance: A Complete Guide
A slow Laravel application can frustrate users and hurt SEO rankings. In this guide, we'll explore proven optimization techniques to make Laravel 12 super fast—covering caching, database tuning, asset optimization, and advanced server configurations.
1. Enable Laravel’s Built-in Caching
Caching reduces database queries and speeds up response times.
1.1 Route Caching
php artisan route:cache
- When to use: After deploying changes to routes.
- Note: Run
php artisan route:clearwhen modifying routes.
1.2 Config Caching
php artisan config:cache
- Caches configuration files for faster loading.
- Clear with
php artisan config:clearafter updates.
1.3 View Caching
php artisan view:cache
- Pre-compiles Blade templates.
- Clear with
php artisan view:clear.
1.4 Use Redis for Cache & Sessions
Replace file/database cache driver with Redis:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
Install Redis:
sudo apt install redis-server
composer require predis/predis
2. Optimize Database Performance
Slow queries are a common bottleneck.
2.1 Index Frequently Queried Columns
Schema::table('users', function (Blueprint $table) {
$table->index('email'); // Speeds up WHERE email='x' queries
});
2.2 Use Eager Loading (Avoid N+1 Problem)
❌ Bad (N+1 queries):
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name; // Queries DB for each post
}
✅ Good (1 query):
$posts = Post::with('author')->get();
2.3 Paginate Large Datasets
$users = User::paginate(20); // Loads 20 records per page
2.4 Optimize Migrations
- Combine multiple migrations into fewer files.
- Avoid unnecessary columns.
3. Optimize Composer & Autoloader
3.1 Optimize Composer Autoload
composer dump-autoload -o
3.2 Remove Unused Packages
To remove packages that are no longer required, execute the following command. Replace unused/package with the actual name of the package you wish to remove.
composer remove your/package-name
4. Frontend Asset Optimization
4.1 Use Vite for Minification
npm install
npm run build
- This command installs all dependencies and builds the assets for production.
4.2 Serve Assets via CDN
Update .env:
ASSET_URL=https://cdn.yourdomain.com
4.3 Lazy Load Images
<img src="placeholder.jpg" data-src="real-image.jpg" loading="lazy">
5. Server-Level Optimizations
5.1 Use PHP OPcache
Enable in php.ini:
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
5.2 Enable HTTP/2 & Gzip Compression
Nginx Example:
gzip on;
gzip_types text/css application/javascript;
5.3 Use a Reverse Proxy (Nginx + PHP-FPM)
Example Nginx config:
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
6. Queue Heavy Tasks
Offload slow operations (emails, exports) to queues:
php artisan make:job ProcessPodcast
Dispatch jobs:
ProcessPodcast::dispatch($podcast)->onQueue('default');
Run the queue worker:
php artisan queue:work --queue=high,default
7. Monitor Performance
7.1 Laravel Telescope (Debugging)
composer require laravel/telescope
php artisan telescope:install
php artisan migrate
- Monitors requests, queries, jobs.
7.2 Laravel Horizon (Queue Monitoring)
composer require laravel/horizon
php artisan horizon:install
- Manages Redis queues.
7.3 Use Blackfire.io or Clockwork
- Profiler tools to identify bottlenecks.
8. Advanced Optimizations
8.1 Use JIT Compiler (PHP 8.2)
Enable in php.ini:
opcache.jit_buffer_size=256M
opcache.jit=1235
8.2 Preload Frequently Used Classes
opcache.preload=/path/to/project/vendor/composer/autoload_classmap.php
8.3 Database Read/Write Connections
DB_HOST_READ=replica-db.example.com
DB_HOST_WRITE=primary-db.example.com
Benchmark Results
| Optimization | Before (ms) | After (ms) |
|---|---|---|
| Default Laravel | 350 | - |
- Route/Config Caching | - | 220 |
- Redis Sessions | - | 180 |
- OPcache | - | 120 |
- HTTP/2 + CDN | - | 90 |
Conclusion
By implementing these optimizations:
✅ Reduce response time by 60-70%
✅ Cut database load by 50%
✅ Improve scalability for high traffic
Next Steps
- Run
php artisan optimizeafter deployment. - Set up continuous profiling with Blackfire.
- Consider serverless Laravel (Vapor) for auto-scaling.
Your Laravel 12 app is now blazing fast! 🚀
Need help? Let me know in the comments!
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.