Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeannoel's avatar

Eager loading

Hi,

I'm new in Laravel (5) and i have a little question. First, i have 3 tables (with SoftDeletes and Timestamps columns ) : Users with primary id : uid Pages with primary id : pid Relation with primary id : 'uid - pid'

Classical indeed. I would like to be able to retrieve all Pages which have a relation and relative to a User and in one "query".

Pages::with('owner')->where('uid', '=', $uid);

It doesn't work at all. I think it easy but i can't find the solution :(

Bye !

0 likes
4 replies
JeroenVanOort's avatar

What do you mean by 'It doesn't work at all.'? Do you get any errors? Or just a huge amount of queries?

pmall's avatar
pmall
Best Answer
Level 56

You want all the pages from an user ??

$user = User::finsOrFail($uid);
$pages = $user->pages;

Don't worry about one or two queries. Even eager loading would make two queries. With eloquent you should expect at least one query per relationship it is the way it works.

By the way I see you have a Pages model, it should be singular, Page, it is the convention.

jeannoel's avatar

Okay pmall, so eager loading make other queries too. It's no 'so magical' :)

pmall's avatar

@jeannoel

Okay pmall, so eager loading make other queries too. It's no 'so magical' :)

It is magical when you get a collection and its relationships.

$users = User::with('pages')->get();

foreach ($users as $user) {

    $pages = $user->pages;

}

The code above execute only two queries, without eager loading it would execute one query for the users and one query for each set of user pages.

It does not allow to retrieve everything with one query, it allows to execute only a constant number of queries whatever the number of models you are fetching.

Please or to participate in this conversation.