Blog Detail

06

Jan
Add methods to Laravel models with Laravel-macroable-models cover image

arrow_back Add methods to Laravel models with Laravel-macroable-models

Laravel macroable models is a package for adding methods to Laravel models on the fly. This package offers developers an easy way of programmatically adding methods to Laravel Eloquent models. Behind the scenes, it makes use of Laravel’s own macroable trait. For more details, check this post.

Installation

You can install this package via composer by running this command:

composer require javoscript/laravel-macroable-models

Usage example

The package provides a Facade to facilitate access to its functionality. Alternatively, you can access it through the app(‘macroable-models’) helper.

For obvious reasons, macros should be added to the model before other parts of the system make use of it. Because of this, the boot method of Service Providers is a good place to start adding macros.

For example, adding a method to the \App\User model in AppServiceProvider:

// app/Providers/AppServiceProvider.php

// ...

use \Javoscript\MacroableModels\Facades\MacroableModels;
use \App\User;

// ...

public function boot()
{

    MacroableModels::addMacro(User::class, 'sayHi', function() {
        return 'Hi!';
    });

}

After adding the macro to the User model, now every instance of this Eloquent model will have the sayHi() method available. We can quickly verify this within artisan tinker:

php artisan tinker

>>> \App\User::first()->sayHi()
=> "Hi!"

In a dedicated MacrosServiceProvider file

If you want to keep multiple macro definitions together, then adding a Service Provider for this purpose might be a good idea.

You can generate a new Service Provider with artisan:

php artisan make:provider MacrosServiceProvider

Then, you should add it to the providers array in the config/app.php file.

// config/app.php

$providers = [
 
    App\Providers\MacrosServiceProvider::class,
   
];

Then, in the boot method of this new Service Provider, you can centralize macro definitions:

// app/Providers/MacrosServiceProvider.php

use \Javoscript\MacroableModels\Facades\MacroableModels;
use \App\User;


public function boot()
{
    
    MacroableModels::addMacro(User::class, 'sayHi', function() {
        return 'Hi!';
    });
    
    MacroableModels::addMacro(User::class, 'sayBye', function() {
        return 'Bye bye';
    });
    
}

Available methods

There are many methods available that will use the \App\User model so that you can try the examples on a fresh Laravel application. Any class that extends the Illuminate\Database\Eloquent\Model class can be extended with these macros.

addMacro(Model::class, 'macroName', function() {}) : void

The most important method of this package, and the one you will most likely be using the most. Add a macro with the name, macroName to the model Model::class.

After the macro has been added, you can call the method on the model as you normally would.

MacroableModels::addMacro(\App\User::class, 'sayHi', function() { return "Hi!"; });

\App\User::first()->sayHi();

With parameters

The defined macro function can receive any number and type of parameters.

MacroableModels::addMacro(\App\User::class, 'say', function(string $something) { return $something; });

$user = \App\User::first();
$user->say("Hello world!");

Context binding… the correct $this

On the macro function, you have access to the $this object, which references the instance of the model that is executing the function.

MacroableModels::addMacro(\App\User::class, 'getId', function() { return $this->id; });

\App\User::first()->getId();

There are also many other methods available in this package.

  • Adding relationships
  • Overriding existing macro
  • Model’s methods precedence
  • removeMacro(Model::class, ‘macroName’) : boolean

You can see the details of all methods with code examples on Github.

Published at : 06-01-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project