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

lonelearner's avatar

Query building with Eloquent Models

How do I build the below query with Eloquent Models?

select users.*, posts.* from users, posts where users.id = 1 and users.id = posts.user_id and posts.status = 'draft'

0 likes
7 replies
MichalOravec's avatar
$user = User::with(['posts' => function ($query) {
    $query->where('status', 'draft');
}])->findOrFail(1);
1 like
lonelearner's avatar

What about if I wanted to build the query with the authenticated user? Is this how I will go about it?

auth()->user()->with(['posts' => function($query) { 
     $query->where('status', 'draft');
}])->get();

NB: Would have tried this out myself to see if it works, but currently in transit and typing this from my phone.

lonelearner's avatar

If I may ask, in your first answer, you used with(). Why was it appropriate for the first answer and not the second? Thanks.

lonelearner's avatar

Thanks so much for taking your time to explain. It's so much appreciated. Will read more on the topic.

Please or to participate in this conversation.