How to Create and Use Custom Laravel Macro
In Laravel, a macro is a way to extend the functionality of a particular class or object with new methods, without having to modify the underlying code.
Macros can be defined on many different classes in Laravel, including Eloquent models, database query builders, and more.
For example, let's say you want to add a new method to the Illuminate\Support\Collection
class that returns the average value of the collection. You can define the macro in your AppServiceProvider
class’s boot()
method:
use Illuminate\Support\Collection;
public function boot()
{
Collection::macro('averageValue', function () {
return $this->sum() / $this->count();
});
}
You can then use this method like any other method on a Collection
object:
$collection = collect([1, 2, 3, 4, 5]);
$average = $collection->averageValue(); // returns 3
Before creating a Laravel Macro, you have to make sure your targeted class uses the Macroable
trait. Please navigate the page to see all available macroable classes.
Overall, macros are a powerful tool in Laravel that allow you to add custom functionality to existing classes in a clean and organized way. 👍
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.