Avoid repeating yourself with Laravel Model Scopes

Photo by Brett Jordan on Unsplash

Setup

Problem

$blog->posts->sortByDesc('published_at')->take(3)

Writing a model scope

public function scopeRecent($query)
{
return $query->orderByDesc('published_at')->limit(3);
}
$blog->posts()->recent()->get()
public function scopeRecent($query, $count)
{
return $query->orderByDesc('published_at')->limit($count);
}

Some extra notes

/*
* @method mixed recent() Fetches recent items
*/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store