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

bradlilley's avatar

Retrieving nested Eloquent records for authenticated user.

I have three three tables.

users
    id - integer
    email - string

clients
    id - integer
    user_id - integer
    name -string

audits
    id - integer
    client_id - integer
    address - string

The tables are related as follows:

A User has many Clients.

A Client has many Audits and belongs to a User.

An Audit belongs to a Client.

When an authenticated user visits /audits I would like to return a list of all audits owned by clients owned by the user. I can use the query builder to manually join the tables and get what I need but I was hoping that there was a more elegant solution using Eloquent.

I know that I can fetch the parent relationship for audits by calling Audit::with('client'); but I don't know how to query off of the related clients user_id to limit the returned collection.

Is there a way to retrieve nested relationship data with Eloquent or should I just use the query builder and joins?

0 likes
1 reply
TiborBesze's avatar

Oh, it's really easy with Eloquent. Just do something like this:

$user = Auth::user();

$user->load('clients.audits');

This will "lazy eager load" the user's clients and all of its clients' audits.

Then you can just iterate through it in your Blade template, or anywhere you'd like. For example:

@foreach ($user->clients as $client)
    @foreach ($client->audits as $audit)
        {{ dump($audit) }} // or do whatever you'd like
    @endforeach 
@endforeach

Read more here, under the sub heading "Nested Eager Loading":

https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

Please or to participate in this conversation.