I see it very good. This is exactly what an accessor is for.
Jan 3, 2018
4
Level 1
Best practice (pattern) for a method on model
Hi,
i have a question on what is the best practice pattern with this situation.
I have a Pages repository and Page model. And I need to get pageviews for all pages.
I have a simple Controller like this:
public function index(Pages $pages)
{
$pages = $pages->all();
return view('pages.index', [
'pages' => $pages
]);
}
And in the model this method:
public function getPageviewsAttribute(){
$cachekey = Auth::user()->id.'_pageviews_count_'.$this->id;
$count = Cache::driver('user')->remember($cachekey, 15, function () {
return DB::select('...')[0]->count;
});
return $count;
}
This is accessor to appended pageviews property. I can then use $page->pageviews right in the view.
But this is not a good practice, is it? Too much logic in the model, with Cache, Auth and so on.
Where should this be? Not in Controller, right? In repository? How? Somewhere else? What is a good pattern?
Thank you very much.
Please or to participate in this conversation.