Configuration Caching
In production, always cache your configuration:
# Cache configuration files
php artisan config:cache
# Cache routes
php artisan route:cache
# Cache views
php artisan view:cache
# Cache events
php artisan event:cache
# All at once
php artisan optimize
OPcache Configuration
Properly configured OPcache can dramatically improve performance. Add to your php.ini:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=64
opcache.max_accelerated_files=30000
opcache.validate_timestamps=0
opcache.save_comments=1
opcache.enable_file_override=1
Queue Workers
Offload heavy tasks to background queues:
<?php
namespace App\Jobs;
use App\Models\Order;
use App\Services\InvoiceService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class GenerateInvoice implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 60;
public function __construct(
public Order $order,
) {}
public function handle(InvoiceService $invoiceService): void
{
$invoiceService->generate($this->order);
}
public function failed(\Throwable $exception): void
{
// Handle failure - notify admin, log error, etc.
}
}
// Dispatch the job
GenerateInvoice::dispatch($order)->onQueue('invoices');
Lazy Collections
Process large datasets without running out of memory:
<?php
// Bad - loads all users into memory
$users = User::all();
foreach ($users as $user) {
$this->sendNewsletter($user);
}
// Good - processes one at a time
User::lazy()->each(function (User $user) {
$this->sendNewsletter($user);
});
// With cursor for even better memory usage
User::cursor()->each(function (User $user) {
$this->sendNewsletter($user);
});
// Chunk with lazy for batch processing
User::lazy(1000)->each(function (User $user) {
$this->sendNewsletter($user);
});
Database Connection Pooling
Configure persistent connections for better performance:
<?php
// config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'options' => [
PDO::ATTR_PERSISTENT => true,
],
],
Conclusion
Performance optimization is an ongoing process. Profile your application regularly, cache aggressively, and use queues for heavy operations.