Kousha
Kousha

Reputation: 36189

Laravel Caching the Eloquent

What is the difference between caching an Eloquent model with

$myResult = Model::remember(5)->get();

and using the Cache itself:

$myResult = Cache::remember('myModel', 5, function(){
    return Model::get();
});

Are they identical, or is each used for a different purpose?

Upvotes: 2

Views: 1925

Answers (1)

Laurence
Laurence

Reputation: 60038

You are caching the same thing - but in two different ways. They are technically identical (the same query result is cached in both examples for 5 minutes) - but they are different from a "separation of concerns" issue.

When you deal with a Model - perhaps it is in your controller - your Controller should have no real knowledge of the 'inner' workings of the Model. It should just ask for information, and be given the right information.

So using your examples - we have two ways a controller could be built:

Firstly - we could let the controller know "too much" and do this:

function showUser($id)
{
    $myResult = Cache::remember('myModel', 5, function(){
        return Model::find($id);
    });
}

In this example - the controller knows the inner works of the model, and it is also dictating how long the cache should be. But the controller should have no knowledge of what a user is, or how long it should be cached for - that is best left up to the Model to manage. i.e. what happens if you look for a user elsewhere in your code - you have to duplicate you caching.

Meanwhile you could do it this way instead:

function showUser($id)
{
      $user= User::getUser($id);
}

and then in your User Model

function getUser($id)
{
      return User::remember(5)->find($id);
}

This way the management of the user remains inside the model. The model knows how long (if at all) a user should be cached for. (Yes - some people will say caching should be abstracted from the model into a repository - but lets keep it simple for now). In this example the controller has no idea that the result is cached - but it doesnt need to nor should it - all it needs is the user with an id of $id

Upvotes: 7

Related Questions