Laravel Query Builder with Macros & Higher-Order Functions

Websolutionstuff | Oct-11-2024 | Categories : Laravel

Hello, laravel web developers! In Laravel, the Query Builder is a powerful tool for building database queries, but sometimes, we need to extend its functionality to handle more complex scenarios.

In this article, I’ll show you how to customize Laravel’s Query Builder using macros and higher-order functions. This allows us to create reusable logic for tasks like complex filtering, sorting, and data aggregation.

Laravel Query Builder with Macros & Higher-Order Functions

Laravel Query Builder with Macros & Higher-Order Functions

 

Step 1: Creating a Custom Macro

Laravel allows you to define custom macros that extend the functionality of existing classes, including the Query Builder. Macros can be defined in the AppServiceProvider or a dedicated service provider.

App\Providers\AppServiceProvider.php

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Builder::macro('whereLike', function ($column, $value) {
            return $this->where($column, 'LIKE', '%' . $value . '%');
        });
    }

    public function register()
    {
        //
    }
}

This macro adds a whereLike method to the Query Builder, allowing us to perform "LIKE" queries more concisely

 

Step 2: Using the Custom Macro

Once the macro is defined, you can use it in your query just like any other Query Builder method

$users = DB::table('users')
    ->whereLike('name', 'John')
    ->get();

In this example, the whereLike macro simplifies searching for users whose names contain "John."

 

Step 3: Creating Higher-Order Functions for Reusability

Higher-order functions allow you to encapsulate logic into reusable methods. In this example, we’ll create a higher-order function to handle sorting.

use Illuminate\Database\Eloquent\Builder;

Builder::macro('applySorting', function ($column, $direction = 'asc') {
    return $this->orderBy($column, $direction);
});

This applySorting function can be reused across different queries for sorting purposes.

 

Step 4: Using the Higher-Order Function

Now that we’ve created the applySorting macro, we can use it in queries.

$sortedUsers = DB::table('users')
    ->applySorting('created_at', 'desc')
    ->get();

This query will return users sorted by their creation date in descending order.

 

Step 5: Combining Macros and Higher-Order Functions

You can combine multiple macros and higher-order functions to build complex query logic.

$filteredSortedUsers = DB::table('users')
    ->whereLike('email', 'example.com')
    ->applySorting('created_at', 'desc')
    ->get();

In this case, we’re filtering users by email and then sorting the results by creation date.

 

Step 6: Data Aggregation Example

Let’s add an aggregation example using a custom macro for summing values.

Builder::macro('sumColumn', function ($column) {
    return $this->sum($column);
});

// Using the sumColumn macro
$totalSales = DB::table('orders')
    ->where('status', 'completed')
    ->sumColumn('total_amount');

Here, we use the sumColumn macro to calculate the total sales for completed orders.

 


You might also like:

Recommended Post
Featured Post
Install and Use Trix Editor in Laravel 11
Install and Use Trix Editor in...

Hello, web developers! In this article, I will show you how to install and use Trix Editor in a Laravel 11 application,...

Read More

Aug-28-2024

How To Upload Large CSV File Using Queue In Laravel 9
How To Upload Large CSV File U...

In this article, we will see how to upload a large CSV file using queue in laravel 9. Here we will learn large numb...

Read More

Sep-16-2022

Laravel 11 CRUD with Image Upload Example
Laravel 11 CRUD with Image Upl...

In this article, we'll see laravel 11 crud with an image upload example. Here, we'll perform a crud operation on...

Read More

Apr-26-2024

How To Downgrade PHP 8 to 7.4 in Ubuntu
How To Downgrade PHP 8 to 7.4...

As a web developer, I understand the significance of embracing the latest technologies to stay ahead in the dynamic worl...

Read More

Aug-04-2023