Adding Cache to your Laravel Site

Posted: 2015-05-22 02:21:06

Using Laravel's built in Cache facade is super easy. I will quickly cover how to use it for showing your Posts and showing a Post.

Example 1 Show a Post

This example will first check the Cache to see if there is a match for post_ID of the post if not it will make one. Also I happen to do the same for the sidebar.

public function show($id)
        $post = Cache::rememberForever('post_' . $id, function() use ($id)
            return Post::findOrFail($id);

        $posts = Cache::rememberForever('posts_sidebar', function()
            return Post::all()->sortBy("created_at", null, TRUE);

        $active = $post->id;
        return View::make('', compact('post', 'posts', 'active'));

Of course this could be moved into a Service and out of the Controller.

It really is that simple

All Posts

Same thing.

If you are not authenticated, eg all users but me, and there is no posts cache make one else show it.

if(Auth::user()) {

            $posts = Post::OrderByCreatedAt()->get();

        } else {

            $posts = Cache::rememberForever('posts', function()
                return Post::Published()->OrderByCreatedAt()->get();


Clearing Cache

For this I made a PostsObeserver Class

This will reset Cache for the related caches whenever a post is made or updated.

use Illuminate\Support\Facades\Cache;

class PostObserver {

    public function saved($model)
        foreach(['posts_sidebar', 'posts'] as $value)

        Cache::forget('post_' . $model->id);

Then I register it in the model

public static function boot() { parent::boot(); Post::observe(new PostObserver()); }


laravel cache