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

Why is it sometimes orderBy and sometimes sortBy?

Telling your editor/IDE about magic methods

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s Start a Journey With JavaScript

Making WebSocket in Sync With User Internet Connectivity in React Using Redux Part 2

Why Lodash is not a foolproof Comparer for JavaScript objects?

Web Scraping with a Headless Browser: A Puppeteer Tutorial

API Penetration Testing: Using ZAP Automation Framework

Which RxJS operators to use within NgRx Effects?

Debugging React Native Apps in VSCode

The power of two-way data binding

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
Adam Hopkinson

Adam Hopkinson

More from Medium

Laravel 9 released!

How to generate custom error page in Laravel

Create an array and access array elements in PHP

Sharing data to all view Laravel Blade