DEV Community

Cover image for Crafting a Laravel Search Macro: A Quick Guide
Dharmik Bhadkoliya
Dharmik Bhadkoliya

Posted on

Crafting a Laravel Search Macro: A Quick Guide

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
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

(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
Enter fullscreen mode Exit fullscreen mode

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}%");
        });
    }
Enter fullscreen mode Exit fullscreen mode

(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;
        });
    }

Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
thomasmoors profile image
Thomas Moors

What is the benefit over using Laravel Scout with the db driver?

Collapse
 
dharmik225 profile image
Dharmik Bhadkoliya
Collapse
 
thomasmoors profile image
Thomas Moors

Could you please elaborate? Just the link to the Scout docs doesn't answer my question.

Thread Thread
 
dharmik225 profile image
Dharmik Bhadkoliya

Using Laravel Macros is beneficial over Laravel Scout with the database driver because Macros are lightweight and easy to customize. They offer a simpler solution for basic search needs without needing external dependencies. Laravel Scout, on the other hand, excels in advanced features like full-text search and scalability, but it comes with extra dependencies and setup complexity. Opting for Laravel Macros is a good choice when you want simplicity and control, especially for projects with straightforward search requirements. However, the decision between the two depends on the specific needs and complexity of your project.