Optimize Laravel 12 for Maximum Performance: A Complete Guide

Author

Kritim Yantra

Mar 26, 2025

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:clear when modifying routes.

1.2 Config Caching

php artisan config:cache
  • Caches configuration files for faster loading.
  • Clear with php artisan config:clear after 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.
  • Minifies JS/CSS.
  • Versioning for cache busting.
  • 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

    1. Run php artisan optimize after deployment.
    2. Set up continuous profiling with Blackfire.
    3. Consider serverless Laravel (Vapor) for auto-scaling.

    Your Laravel 12 app is now blazing fast! 🚀

    Need help? Let me know in the comments!

    LIVE MENTORSHIP ONLY 5 SPOTS

    Laravel Mastery
    Coaching Class Program

    KritiMyantra

    Transform from beginner to Laravel expert with our personalized Coaching Class starting June 10, 2025. Limited enrollment ensures focused attention.

    Daily Sessions

    1-hour personalized coaching

    Real Projects

    Build portfolio applications

    Best Practices

    Industry-standard techniques

    Career Support

    Interview prep & job guidance

    Total Investment
    $200
    Duration
    30 hours
    1h/day

    Enrollment Closes In

    Days
    Hours
    Minutes
    Seconds
    Spots Available 5 of 10 remaining
    Next cohort starts:
    June 10, 2025

    Join the Program

    Complete your application to secure your spot

    Application Submitted!

    Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

    What happens next?

    • Confirmation email with program details
    • WhatsApp message from our team
    • Onboarding call to discuss your goals

    Comments

    No comments yet. Be the first to comment!

    Please log in to post a comment:

    Sign in with Google

    Related Posts

    Laravel 12 CRUD Application with React, InertiaJS & Tailwind CSS
    Kritim Yantra Kritim Yantra
    Feb 27, 2025
    Laravel 12 Multi-Auth System: Implementing Separate Admin and User Tables
    Kritim Yantra Kritim Yantra
    Feb 28, 2025
    Laravel 12 Roles and Permissions Setup: Complete Guide
    Kritim Yantra Kritim Yantra
    Feb 28, 2025