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

SigalZ's avatar

Eloquent 'with' - what does it do?

Hello,

I don't understand what does 'with' do.

I have this relationships on Customer model:

public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

If I use this code:

Customer::with('user')->ddRawSql();

I get this query:

select * from customers

so what is the point of 'with'?

Where does it come into play?

If I need to search or order by a column from 'users' table I can't use 'with'.

I don't get what is it for. Eager loading, where does the eager loading happens?

Thank you.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

use debugbar rather than to sql.

You will see that there are two queries, the first to get all the customers (you don't constrain that) and then to get the related models (your with('user')) the results are then merged in memory.

Yes, it is to eager load the users so that there is not later a query per user as you iterate through the customers and cause an n+1 performance issue.

1 like

Please or to participate in this conversation.