Performance has always been one of the most discussed topics in Laravel, yet it has brought fresh perspectives to many PHP developers. Let’s optimize this framework once again.
Fundamentals (Common Knowledge)
- Use Redis drivers for caching, sessions, and queues
- Framework built-in caching:
- Route caching:
php artisan route:cache - Configuration caching:
php artisan config:cache
- Route caching:
- Implement caching based on API idempotency
Upgrades
OPcache:- Enable it without hesitation
- Set
opcache.validate_timestamps=0to prevent automatic code updates in production (similar to compiled languages). Restartphp-fpmafter each deployment - Reference: Best Config for Zend OPcache
Remove Unnecessary Middleware
- Remove CORS middleware if your API only serves mobile apps
- Remove default API rate limiting middleware if unsuitable for your scenario
Reduce Service Providers
- Disable unnecessary services for pure API projects:
- View services
- Session services
- Password reset services
Let’s focus on hybrid projects containing both API and Admin interfaces (using full-stack frameworks like Laravel-admin or Dcat Admin).
Since Laravel 5.5 introduced package auto-discovery, we can optimize service providers by:
- List registered service providers:
php artisan package:discover
Discovered Package: dcat/laravel-admin
Discovered Package: facade/ignition
...
- Disable auto-discovery for specific packages in
composer.json:
"extra": {
"laravel": {
"dont-discover": ["dcat/laravel-admin"]
}
}
- Conditionally register service providers in
AppServiceProvider.php:
public function boot()
{
if (config('admin.enable')) {
AliasLoader::getInstance()->alias('Admin', Admin::class);
$this->app->register(AdminServiceProvider::class);
}
}
This optimization achieved 40% performance improvement (tested on 2vCPU/4GB machine with OPcache enabled):
Q&A: Disabling View Services
- Comment out in
config/app.php:
// Illuminate\View\ViewServiceProvider::class,
// Illuminate\Notifications\NotificationServiceProvider::class,
// Illuminate\Pagination\PaginationServiceProvider::class
- Modify
Exceptions/Handler.phpfor API error handling:
public function render($request, Exception $exception)
{
if ($request->is('api*')) {
return (new Response(json_encode([
'code' => 500,
'msg' => $exception->getMessage()
])))->withHeaders(['Content-Type' => 'application/json']);
}
return parent::render($request, $exception);
}