Thomas Jensen
Thomas Jensen

Reputation: 2198

Caching relationships eager loaded in the model (protected $with) with Laravel and Eloquent

In my Article model I eager load the category relationship within the model:

protected $with = array('category');

When I get my articles in the controller I cache the results of both my articles and the relationships I eager load there:

$articles = Article::with([
   'owner' => function ($q) {$q->remember(10);},
   'tags' => function ($q) {$q->remember(10);},
   'thumbnail' => function ($q) {$q->remember(10);}
   ])
   ->remember(10)->get();

But; article.category does not get cached. I thought it would get cached together with the Article model, since it is eager loaded in that model. But this does not happen.

It does however get cached if I eager load (with cache) in the controller by adding this to my Article::with:

'category' => function ($q) {$q->remember(10);}

I know that I can remember() the relationship itself:

public function category()
{
    return $this->belongsTo('Category', 'category_id')->remember(10);
}

But then it will always be cached, I would like to define whether and for how long it is cached in the controller. As the values may vary with use.

Is that possible? Or must the caching be defined in the model, since the eager loading happens there?

Upvotes: 1

Views: 3380

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Just use with('category' => ... in your controller.

You might want to extract this to a repository though, so you don't stuff your controller with all that logic. And repositories are trendy nowadays ;)

Search for repository pattern to learn more.

In laravel world repository mostly refers to an abstraction over the storage layer (be it db and eloquent or anything else), that will decouple your controllers from the persistence engine you're using.

And what's more important, it allows easier testing of your code.

Upvotes: 3

Related Questions