Introduction
Laravel Boost is a lightweight package that supercharges your Laravel application's performance by providing intelligent caching, query optimization, and route pre‑loading. In this tutorial we will install, configure, and use Laravel Boost in a real‑world project.
1. Installation #
Run the Composer command:
composer require laravel/boost
The package registers a service provider automatically (Laravel 5.5+). If you are on an older version, add the provider manually in config/app.php:
'providers' => [
// ... other providers
Laravel\Boost\BoostServiceProvider::class,
];
2. Publishing the Configuration #
php artisan vendor:publish --tag=boost-config
You will now have a config/boost.php file. Important options:
cache_driver– which cache driver to use (default:redis).query_cache_ttl– time‑to‑live for cached queries.route_preload– boolean to enable route pre‑loading.
3. Basic Usage #
3.1 Caching Queries #
Wrap any Eloquent query with Boost::remember():
use Laravel\Boost\Boost;
$users = Boost::remember(300, function () {
return User::where('active', true)->get();
});
The result will be cached for 300 seconds using the driver you configured.
3.2 Route Pre‑loading #
Add the BoostRoute middleware to your web group in app/Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
// ... other middleware
\Laravel\Boost\Middleware\BoostRoute::class,
],
];
Now the first request to each route stores a compiled version on disk, reducing bootstrap time for subsequent hits.
4. Advanced Configuration #
4.1 Tag‑Based Cache Invalidation #
You can tag cached queries for selective flushing:
Boost::rememberTag('users', 600, function () {
return User::all();
});
// Later, when a user is updated:
Boost::flushTag('users');
4.2 Auto‑Pruning Stale Cache #
Enable auto_prune in config/boost.php to let the package clean up expired entries automatically via a scheduled command:
php artisan schedule:run
Add the following to app/Console/Kernel.php:
protected function schedule(Schedule $schedule)
{
$schedule->command('boost:prune')->hourly();
}
5. Testing the Impact #
Run Laravel Telescope or Laravel Debugbar before and after enabling Boost. You should see:
- Reduced DB query count.
- Lower request execution time.
- Faster route resolution.
6. Common Pitfalls #
- Cache driver mismatch: Ensure the same driver is configured in
cache.phpandboost.php. - Large payloads: Avoid caching massive result sets; use pagination.
- Stale data: Remember to flush tags when underlying data changes.
7. Conclusion #
Laravel Boost offers a zero‑configuration start for performance gains and fine‑grained control when you need it. Combine it with queue workers and Horizon for a truly scalable Laravel stack.
Happy coding!