Understanding Laravel’s Macroable trait

Laravel makes heavy use of the Macroable trait throughout its codebase, but the official documentation only mentions it in passing. There’s no explanation of its purpose, or when you should (and shouldn’t) use it. Let’s dig in.

Understanding Laravel’s Macroable trait

Laravel route collection binding

Route model binding is a very useful Laravel feature. But what happens if you have an endpoint which needs to support multiple, comma-delimited IDs?

Route collection binding to the rescue.

Laravel route collection binding

A nicer way of overriding Eloquent global scopes

The standard method for removing a global scope from an Eloquent model is a little clunky. We can do better.

A nicer way of overriding Eloquent global scopes

Laravel’s mysteriously macroable paginators

Laravel’s Macroable trait is a very neat way to add new functionality to built-in classes.

I recently found myself with the need to add a custom method to the LengthAwarePaginator class. Not a problem, I thought, I’ll write a quick macro.

A fine solution, but for the fact the LengthAwarePaginator isn’t “macroable”. Or so it would seem at first glance.

Laravel’s mysteriously macroable paginators

Eager loading Eloquent properties

A simple, performant solution for eager-loading Eloquent relationships, when you’re only interested in one or two specific properties on the related model.

Eager loading Eloquent properties

Cleaner code with Eloquent events

Eloquent makes it easy to respond to certain key points in the lifecycle of a model instance, by exposing events such as creating, updating, and deleted.

Cleaner code with Eloquent events

Eloquent attributes and database defaults

There’s an important gotcha to remember when working with Eloquent and default database values: if you create a new model instance, without overriding a default value, the attribute will not be set.

There are three easy solutions to this problem. As you might expect, each comes with its own set of pros and cons.

Eloquent attributes and database defaults