PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

How to build a Searching Macro in Laravel

How to build a Searching Macro in Laravel

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)

loading comments