Laravel Macros for Collections and Eloquent

One great bit about using Laravel is the ease of use of Eloquent models and Collection objects in general. Illuminate\Support\Collection has so many handy methods which make it easier to handle data and to write readable code.

$squareRoots = collect([1, 4, 9, 16])->map(function($number)  {
    return sqrt($number);

Occassionally we can find ourselves writing the same bit of code for many different collections. In that case it can be useful to extend Illuminate\Support\Collection to add our own custom method, and for this we can use Macros:

use Illuminate\Support\Collection;

Collection::macro('squareRoot', function() {
    return $this->map(function($number) {
        return sqrt($number);

The big advantages here, aside from the reusability, are the fact that we can continue to chain methods off the collection and the code looks like it belongs to the framework:

collect([1, 2, 3, 4])->squareRoot();
collect([2, 4, 6, 8])->squareRoot()->doSomethingElse();

A good place to put the Macro is in a Service Provider, so that it is available to all collections on boot.

Macros can also be used for Eloquent Relationships, for example to convert a has-many relationship into a has-one.

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

HasMany::macro('toHasOne', function() {
    return new HasOne(

Now, inside a model, it's possible to convert any has-many relation. This means it's no longer necessary to always get the first value from the collection!

public function posts() {
    return $this->hasMany(Post::class);

public function latestPost() {
    return $this->posts()->latest()->toHasOne();

To be honest, I can't think of any other example for Eloqent Relations Marcros than converting has-many to has-one. But if you have any other ideas, it would be cool to learn about them in the comments! Here is a repo on Github which shows an example of using the toHasOne Macro: