Automatic Relation Loading (Eager Loading) in Laravel 12.8


- Laravel 12.8 - Automatic Relationship Loading
- The Problem
- The New Solution: withRelationshipAutoloading()
- Morph Relations Supported
- Manual Loading Still Works
- Global Autoloading
Laravel 12.8 - Automatic Relationship Loading
A new feature has landed in Laravel contributed by @r9ray that aims to simplify how developers handle eager loading of relationships: automatic relationship loading. Merged in PR #53655, this feature removes the need for repetitive load()
and with()
calls, particularly in large projects with deeply nested or dynamic relationships.
The Problem
In large applications, managing which relationships need to be eager-loaded becomes tedious:
$projects->load([ 'client.owner.details', 'client.customPropertyValues', 'clientContact.customPropertyValues', 'status', 'company.statuses', 'posts.authors.articles.likes', 'related.statuses']);
This approach is verbose, hard to maintain, and easy to get wrong—especially when relationships evolve over time or are used conditionally.
withRelationshipAutoloading()
The New Solution: A more elegant approach to handling nested eager loading with the withRelationshipAutoloading()
method. When applied to a model or collection, it automatically loads relationships whenever they are accessed, without the need for explicit load()
or with()
calls.
$orders = Order::all()->withRelationshipAutoloading(); foreach ($orders as $order) { echo $order->client->owner->company->name;}
As you navigate through the relationships, Laravel silently loads the necessary data in the background—no manual calls required.
Morph Relations Supported
Polymorphic (morph) relations are fully supported. When using morphs, only the accessed type is loaded, which keeps the process efficient.
Manual Loading Still Works
You can still use load()
or with()
manually, and Laravel won't reload relationships you've already explicitly loaded.
Global Autoloading
If you want this behavior application-wide, you can enable it globally:
Model::automaticallyEagerLoadRelationships();
This saves time for teams that rely heavily on nested or dynamic relationships, reducing overhead and improving maintainability.
Check out the full PR here: laravel/framework#53655
Stay Updated.
I'll you email you as soon as new, fresh content is published.