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

Simple coreDNS timestamp log

React Native Firebase Cloud Functions

YouTube Video | DOM Crash Course -1

Creating Facebook Chat Head Bubbles in React Native | by Andi Gu

Creating Facebook Chat Head Bubbles in React Native | by Andi Gu

How to start up a Node js backend using Express

Understand the Call Stack, Callbacks, and Higher-Order Functions in JavaScript

How to Implement OpenID Connect Authentication Flow Inside of an iFrame

Performance metrics. What’s this all about?

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

URLs manipulation in PHP (the easy way)

Change your URLs with a simple fluent PHP class

How to use Scopes in Laravel

Why You Should Use Laravel Development For Skyrocket Your Business In 2022?

What’s New In Laravel 9 (Part 1)