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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 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.