How to build a Searching Macro in Laravel

How to build a Searching Macro in Laravel

Written by jeblister on Nov 21st, 2021 Views Report Post

What is a Macro in Laravel ?

Macro is a powerful feature of the Laravel framework. Laravel Macros allow you to add custom functionality to internal Laravel components. Macros can be defined on any class with the Macroable trait.

Where to use a macro ?

If you find yourself repeating performing logic on Laravel components throughout your system, think about using a macro for better expression and reuse.

Here we will build a macro which will add search for every model on our Laravel project.

Searching macro, the Code

On the App\Providers\AppServiceProvider add a simple :

use Illuminate\Database\Eloquent\Builder;

// ...

Builder::macro('search', function(string $attribute, string $searchTerm) {
   return $this->where($attribute, 'LIKE', "%{$searchTerm}%");
});

Or a more advanced example :


use Illuminate\Database\Eloquent\Builder;

// ...
Builder::macro('search', function($attributes, string $searchTerm) {
foreach(array_wrap($attributes) as $attribute) {
$this->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
   }

return $this;
});

How to use the searching macro #

Now, if you want to add a search, to the User model but to every model, use the macro like so :

// searching a single column

User::search('name', $searchTerm)->get();

// searching on multiple columns in one go
User::query()
->search('user', 'moom')
->search('email', 'gmail')
->get();

Ressources

If you need to take it further. Here's a collection of articles about Macro on Laravel :

The Magic of Laravel Macros

Searching models using a where like query in Laravel | freek.dev

How to Use Laravel Macro With Example? - DZone Web Dev

Laravel Tip: 5 examples of why you should be using Macros

How to Create Response Macros in Laravel?

Happy coding!

Comments (0)