A. Database & Eloquent Optimization
1- Eager Loading (N+1 Problem):
Avoid the N+1 query problem by eager loading relationships when querying models.
Bad (N+1):
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->user->name; // Each user call is a new query
}
Good (Eager Loading):
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // Only 2 queries (Post + User)
}
2- Select Specific Columns:
Don't select all columns select('*') if you only need a few.
$users = User::select('id', 'name', 'email')->get();
3- Use Indexes:
Ensure your database columns that are frequently used in WHERE, JOIN, ORDER BY clauses have proper indexes.
Add indexes in your migrations:
$table->string('email')->unique(); // Unique automatically creates an index
$table->index('category_id'); // Custom index
4- Pagination for Large Datasets:
Never load all records if you have a large table. Use paginate() or simplePaginate().
$users = User::paginate(15);
5- chunk() for Processing Large Datasets:
When processing many records (e.g., for background jobs), use chunk() or cursor() to avoid loading all records into memory at once.
Post::chunk(200, function ($posts) {
foreach ($posts as $post) {
// Process post
}
});
6- exists() instead of count() for existence checks:
If you just need to know if a record exists, exists() is more efficient than count() as it stops at the first match.
if (User::where('email', $email)->exists())
{ /* ... */ }
B. Caching
1- Route Caching:
If you have many routes, caching them significantly speeds up route registration.
Run in production: php artisan route:cache
Remember to clear it php artisan route:clear and re-cache after any route changes.
2- Configuration Caching:
Combines all your configuration files into a single file for faster loading.
Run in production: php artisan config:cache
Clear php artisan config:clear and re-cache after config changes.
3- View Caching:
Caches your Blade compiled views, so they don't have to be recompiled on every request.
Run in production: php artisan view:cache
Clear php artisan view:clear after view changes.
4- Application Data Caching:
Cache frequently accessed data that doesn't change often (e.g., settings, categories, static content).
Use Cache::remember(), Cache::put(), Cache::get() with a suitable driver (Redis or Memcached are much faster than file-based).
C. Queues (Background Processing)
Offload Heavy Tasks:
Move time-consuming tasks (email sending, image processing, video encoding, complex calculations, third-party API calls) to background queues.
This allows your web requests to return a response quickly, improving user experience.
Example:
Instead of:
Mail::to($user->email)->send(new WelcomeEmail($user));
Use a job:
dispatch(new App\Jobs\SendWelcomeEmail($user));
Remember to configure a queue driver (e.g., database, redis, sqs) and run a queue worker php artisan queue:work.
D. Asset Optimization
1- CDN (Content Delivery Network):
Serve static assets (images, CSS, JS) from a CDN to reduce latency for users geographically distant from your server.
2- Image Optimization:
Compress images before deploying. (using tools like TinyPNG, ImageOptim, or build tools)
3- Minification:
Combine multiple CSS files into one and multiple JS files into one.
Minify CSS and JavaScript to remove whitespace and comments.
E. PHP & Server Environment
1- Use the Latest PHP Version:
Always use the latest stable PHP version. Each new version brings significant performance improvements.
2- Enable OPcache:
OPcache is a PHP extension that caches precompiled script bytecode in memory, avoiding the parsing and compilation on every request. It's crucial for PHP application performance.
Ensure it's enabled and configured correctly in your php.ini.
3- Composer Optimization:
In production, install Composer dependencies without dev dependencies:
composer install --no-dev --optimize-autoloader --optimize-autoloader builds a faster class map.
4- JIT Compiler (PHP 8+):
PHP 8's JIT (Just-In-Time) compiler can provide significant performance boosts for CPU-bound tasks.
Ensure it's enabled and configured in php.ini if your workload can benefit from it.
5- HTTP/2 and GZIP Compression:
Configure your web server (Nginx or Apache) to use HTTP/2 and GZIP compression.
HTTP/2: Allows multiple requests/responses over a single connection, reducing latency.
GZIP Compression: Compresses text-based assets (HTML, CSS, JS) before sending them to the client, reducing bandwidth usage.
6- Proper Server Configuration:
Use a fast web server like Nginx (preferred over Apache for performance).
Tune PHP-FPM settings (e.g., pm.max_children, pm.start_servers) based on your server's resources and traffic.
7- Choose a Good Hosting Provider:
A cheap, overloaded shared host will negate many of your optimization efforts. Invest in a good VPS or dedicated server.
F. Code Quality & Best Practices:
1- Remove Unused Packages & Services:
Audit your composer.json and config/app.php. Remove any packages or service providers you don't actually need.
2- Limit Middleware Usage:
Middleware adds overhead. Only apply middleware where absolutely necessary.
3- Don't Use APP_DEBUG=true in Production:
This is a major performance killer. Set APP_DEBUG=false in your .env for production.
4- Minimize Logging:
Adjust LOG_LEVEL in production (e.g., warning or error) to reduce disk I/O from excessive logging.
Top comments (0)