Crafting a Laravel Search Macro: A Quick Guide
Tags: laravel, php, developer
Published: 2023-12-13 07:33:36

Macro is a powerful Laravel framework feature.You can apply Laravel Macros to expand on the functionality of Laravel components.The Macroable trait allows macros to be defined on any class.

Where can I apply a macro?
If you're doing the same thing over and over again with Laravel components in your system, think about using a macro. It makes your code clearer and easier to reuse.

For example, let's make a macro that adds a search feature to every model in our Laravel project.

Integration Steps:

Step 1: Install Laravel and Create a New Project
First, make sure you have Laravel installed on your computer. If not, you can install it by following the instructions in the official Laravel documentation. After installing Laravel, open your terminal or command prompt and type the following command to create a new Laravel project:


```
composer create-project laravel/laravel MacrosApp
```

If you already have an existing Laravel project, you can use it to build macros and enhance its functionality. Simply navigate to your project's root directory in the terminal and proceed with the following steps.
Step 2: Migrate & Seed the Database
Now that you've set up your Laravel project, the next step is to migrate and seed the database. This will create the necessary tables and populate them with sample data.

(a)Seed the Database:
Open the database/seeders/DatabaseSeeder.php file. You'll find code that seeds the database with sample data. Uncomment this code by removing the // at the beginning of the lines.

```
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder
{
    public function run(): void {
        \App\Models\User::factory(10)->create(); //Uncomment this line
    }
}
```
(b)Run Migrations & Seed:
Open your terminal or command prompt, navigate to your project's root directory, and execute the following command:

```
php artisan migrate --seed
```
Step 3: Create a Search Macro
To enhance search functionality in your Laravel project, we'll add a custom search macro. Open the App\Providers\AppServiceProvider file and define the macro within the boot method.
(a)Add a Simple Search Macro for a Single Attribute

```
use Illuminate\Database\Eloquent\Builder;

//...
public function boot(): void
    {
       Builder::macro('search', function(string $attribute, string $searchTerm) {
                    return $this->where($attribute, 'LIKE', "%{$searchTerm}%");
        });
    }
```
(b)Extend the Search Macro to Handle Multiple Attributes.
To accommodate searching across multiple attributes, we'll modify the search macro to accept an array of attributes.

```
use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Builder;


public function boot(): void
    {
       Builder::macro('search', function($attributes, string $searchTerm) {
        foreach(Arr::wrap($attributes) as $attribute) {
            $this->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
        }
        return $this;
        });
    }
```

This extended search macro allows you to specify an array of attributes, making it more versatile for searching across multiple fields. The orWhere method is used to build a query that matches any of the specified attributes with the given search term.

Step 4 : How to apply the macro for searching
Now, use the following macro to add a search to not just the User model but all models:
Open the routes/web.php file in your project. Add the following code to demonstrate using the search macro in routes.

```
<?php


use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    // searching a single column
    return User::search('email','example.com')->get();

   // searching on multiple columns
   return App\Models\User::search('name', 'mr')->search('email', 'example.org')->get();
});
```
In this example, we are using the search macro to find users by email and perform a combined search by name and email. Adjust the attribute names and search terms based on your actual model attributes.

Conclusion:
To sum it up, this guide shows how to use Laravel macros to make searching in your project easier. With a simple setup process and a search macro that works for one or multiple attributes, your code becomes cleaner and more adaptable. By following the steps and applying the search macro to your controllers & routes, you can quickly add search features to your models, improving your code's simplicity and efficiency.