How to Optimize Laravel for Production: Best Practices
To optimize Laravel for production, use
php artisan config:cache and php artisan route:cache to speed up config and routing. Also, enable OPcache on your server, use queues for heavy tasks, and disable debug mode by setting APP_DEBUG=false in your .env file.Syntax
These commands prepare your Laravel app for production by caching configuration and routes, which reduces load time:
php artisan config:cache- Combines all config files into one cache file.php artisan route:cache- Caches all routes for faster route registration.php artisan view:cache- Compiles all Blade templates to speed up rendering.
Set APP_DEBUG=false in your .env file to disable debug mode and improve security.
bash
php artisan config:cache php artisan route:cache php artisan view:cache
Example
This example shows how to prepare your Laravel app for production by running cache commands and disabling debug mode.
bash
# Run these commands in your terminal inside the Laravel project folder php artisan config:cache php artisan route:cache php artisan view:cache # Then, edit your .env file to disable debug mode # Change APP_DEBUG=true to APP_DEBUG=false
Output
Configuration cached successfully.
Routes cached successfully.
Compiled views cached successfully.
Common Pitfalls
Common mistakes when optimizing Laravel for production include:
- Forgetting to clear caches after config or route changes, causing stale data.
- Leaving
APP_DEBUG=truein production, which exposes sensitive info. - Not enabling PHP
OPcache, missing out on performance boosts. - Running
route:cachewhen using closures in routes, which causes errors.
php
Wrong way: # Using closures in routes and running route cache Route::get('/hello', function () { return 'Hello'; }); php artisan route:cache # This will cause an error because closures can't be cached. Right way: # Use controller methods instead Route::get('/hello', [HelloController::class, 'index']); php artisan route:cache
Output
LogicException: Unable to prepare route [hello] for serialization. Uses Closure.
Quick Reference
Summary tips for Laravel production optimization:
- Run
php artisan config:cache,route:cache, andview:cache. - Set
APP_DEBUG=falsein.env. - Enable PHP
OPcacheon your server. - Use queues for long-running tasks.
- Avoid closures in routes when caching routes.
Key Takeaways
Always cache config, routes, and views before deploying to production.
Disable debug mode by setting APP_DEBUG=false to protect sensitive info.
Enable PHP OPcache for faster PHP execution.
Avoid closures in routes if you plan to use route caching.
Use queues to handle heavy or slow tasks asynchronously.