Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567



Laravel Macroable Models Package – Laravel News

Javier Ugarte released a package called Laravel Macroable Models for adding methods to Laravel models on the fly:

The package offers developers an easy way of programmatically adding methods to Laravel Eloquent models. Behind the scenes, it makes use of Laravel’s macroable trait.

The idea of macorable models has controversy around it, but the package author describes his particular use-case and solution in his writeup about the package. As always, be sure to explore your use-case, and in general macroable models won’t be necessary for most use-cases.

With that said, let’s check out what this package provides:

You can define a macro for a model through a service provider boot() method. The package keeps track of macros for each model.

// app/Providers/AppServiceProvider.php

use JavoscriptMacroableModelsFacadesMacroableModels;
use AppUser;

public function boot()
   MacroableModels::addMacro(User::class, 'sayHi', function() {
        return "Hello, {$this->name}!";


As you can see in the example above, this package takes care of context binding so you can use $this inside macro functions.

Here are a few more functions the package provides:

/* [
] */

// Return all macros for a model
// Get all registered macros

Learn More

I want to reiterate that this package has a narrow, unique use-case. Typically, you wouldn’t need macros to define model methods on-the-fly. I’d recommend reading the author’s writeup about this package and his inspiration behind it.

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:
Laravel Packages

Credit: Source link

Previous Next
Test Caption
Test Description goes like this