Skip to main content

Command Palette

Search for a command to run...

Laravel dynamic relationship attribute

Published
1 min readView as Markdown

Relationship Methods Vs. Dynamic Properties

If you do not need to add additional constraints to an Eloquent relationship query, you may access the relationship as if it were a property. For example, continuing to use our User and Post example models, we may access all of a user's posts like so:

use App\Models\User;

$user = User::find(1);

foreach ($user->posts as $post) {
    //
}

Dynamic relationship properties perform "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model's relations.

More from this blog

Khang Nguyen

119 posts