PeterTheLobster PeterTheLobster - 1 year ago 78
PHP Question

Do Laravel relationship methods like belongsTo always query the database?

I just want to get a better understanding of how Laravel's Eloquent/Model handles relationships.

Let's say I have defined a relationship where each Post has an Author and the Post class has a method for getting the author object associated with it:

public function author() {
return $this->belongsTo( 'App\User', 'author_id' );

Calling the author() method of a post now will return the author based on the author_id field of the post. My question is: Does Laravel make a query each time the method is used? Would the following code ask for the data from the db twice?

<a href="{{ route('user',$post->author->slug) }}">{{ $post->author->name }}</a>

Answer Source

This question, with examples, is perfectly documented right here.

and on stack overflows documentation right here:

Eager Loading Documentation

Both mentions that:

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property.

And that you can

When querying, you may specify which relationships should be eager loaded using the with method:

So when you call $post->author you are making a query just once, and reusing the same data from the previous query onwards.

However, had you done the same too, let's say, multiple posts and looped through them asking for their author, every request would have been a new query. UNLESS the model had protected $with = ['author'] attribute or a with was included in the query to load it eagerly.

$post = App\Post::with('author')->find(2)->get();

All the data will be eager loaded, and only have one executed query.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download