Making sure routes and config files are cached in a Laravel app

In a typical Laravel application, you'll likely to have many routes, config files and possible some events. In your development environment these routes and config files will loaded and registered in each request. The performance penalty for this is not too big.

In a production environment, you want to cache these things. Laravel makes this easy by offering a couple of Artisan commands that you can use in your deployment procedure.

php artisan optimize # will cache routes and config
php artisan event:cache # will cache events

By caching these things, you'll improve the performance of your Laravel app

Using our application health check, you can get notified when things are not cached in production.

Oh Dear will not run any code inside your application or server. Instead, you should perform the checks yourself. Oh Dear will send an HTTP request to your application to a specific endpoint. Your application should respond with JSON containing the result of health checks.

Spatie's Laravel Health package can build up the JSON the Oh Dear expects. Here are the docs on how to do that.

Laravel Health is a package that can detect various problems that are going on with your application and server. It can check disk space, cpu usage, if Horizon is running, and much more.

The package has a new check that makes sure wether routes, config and events are cached.

This is how you can use it. Check in the package can be registered via Health::check() function.

// typically in a service provider

use Spatie\Health\Facades\Health;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;

Health::checks([
		// other checks...

    OptimizedAppCheck::new(),
]);

This check will pass if the config, routes and events are cached.

If you only want to check certain caches, you can call the checkConfig, checkRoutes and checkEvents methods. In this example, we'll only check for cached config and routes.

use Spatie\Health\Facades\Health;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;

Health::checks([
		// other checks,

    OptimizedAppCheck::new()
       ->checkConfig()
       ->checkRoutes(),
]);

With that OptimizedAppCheck in place and Oh Dear app configured, this is what it looks like when something is not cached.

image

This is a Slack notification, but it will look similar on all notification channels we offer.

Want to get started? We offer a no-strings-attached 10 day trial. No credit card required.

Start monitoring »

You're all set in
less than a minute!