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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Macros let you extend framework classes with reusable methods without subclassing.
- 2Registering the same macro on both builders keeps the API consistent across raw and Eloquent queries.
- 3Grouping conditions in a nested closure produces a correctly parenthesized OR within a larger AND.
Related explainers
go
package proxy import ( "log"
Building a hardened Go reverse proxy
reverse-proxy
http
timeouts
Intermediate
7 steps
php
<?php namespace App\Reminders;
Scheduling reminders across time zones in PHP
timezones
datetime
immutability
Intermediate
7 steps
php
<?php namespace App\Http\Middleware;
Verifying GitHub webhook signatures in Laravel
middleware
hmac
webhooks
Intermediate
5 steps
php
<?php namespace App\Models;
How Eloquent scopes model order status in Laravel
query scopes
state machine
eloquent
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/adding-a-whereactive-macro-in-laravel-explained-php-c665/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.