Laravel: How to Add Caching to Everything

Cache is king. Regardless of the application, PHP or otherwise, nearly website or web application can greatly benefit from caching when your site has more than zero users. Caching improves the response speed of your app while helping to keep it online if it suddenly goes viral.

Laravel makes caching easy. Using the Cache interface directly, or by using the Remember() alias during Eloquent and MySQL queries. In PHP, and Laravel, you have many caching options, but we wont explore those here.

// Caching a single variable for later in Laravel
Cache::remember('userName', 'John');

// Using caching on a Eloquent query for 10 minutes
User::where('name', 'John')->remember(10)->first();

The two areas that are less obvious on how to keep your servers grubby little hands off of your database. First, caching eager loaded Eloquent model relationships. And secondly, caching route model bindings for variables you automatically load into your controllers

Cache Eager Loaded Eloquent Relationships

// Cache a Eloquent model relationship for 10 minutes.
User::with([
    'profilePhotos' => function ($query) {
        return $query->remember(10);
     }
])->get();

Cache Route Model Binded Variables

// Bind the variable to the User object and cache it for 10 min
Route::bind('user', function ($value, $route) {
    return User::where('id', $value)->remember(10)->first();
});

// Example using the binding in a route
Route::get('profile/{user}', function (User $user) {
    // View stuff here, or better yet abstract to a Controller
    // then use [email protected] to access
}); 

Now go forth and spread your full caching abilities to keep your web application fast and users happy

Small dog web development studio

View All Our Posts

Web application developers in western Washington, creating user centric web solutions for businesses of all shapes and sizes.

Our projects include ecommerce, event organization, user driven web applications and more.


Small Dog Studios, LLC. Small Dog Studios News