php 26 lines · 5 steps

Adding a whereActive macro in Laravel

A service provider registers a reusable query macro on both the query and Eloquent builders so you can call whereActive() anywhere.

Explained by highlit
1namespace App\Providers;
2 
3use Illuminate\Database\Query\Builder as QueryBuilder;
4use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
5use Illuminate\Support\ServiceProvider;
6 
7class QueryMacroServiceProvider extends ServiceProvider
8{
9 public function boot(): void
10 {
11 QueryBuilder::macro('whereActive', function (bool $active = true) {
12 return $this->where('status', $active ? 'active' : 'inactive')
13 ->whereNull('deleted_at')
14 ->where(function ($query) {
15 $query->whereNull('expires_at')
16 ->orWhere('expires_at', '>', now());
17 });
18 });
19 
20 EloquentBuilder::macro('whereActive', function (bool $active = true) {
21 $this->getQuery()->whereActive($active);
22 
23 return $this;
24 });
25 }
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Macros let you extend framework classes with reusable methods without subclassing.
  2. 2Registering the same macro on both builders keeps the API consistent across raw and Eloquent queries.
  3. 3Grouping conditions in a nested closure produces a correctly parenthesized OR within a larger AND.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Adding a whereActive macro in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code