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

mtdesigners's avatar

Laravel query multiple models with ORM

I'm trying to make a query that includes to related tables/models:

Post Model:

public function user()
    {
        return $this->belongsTo(User::class);
    }

Post Controller:

'posts' => Post::with('user')->where(user->approved)->where('approved' , true)->latest(),

The code above is wrong of course but I want to achieve something similar. To list all the posts where both the post and user who posted that are approved. There are 2 column called 'approved' in both tables. Should I just use join and then query that, or is it possible to use Eloquent? Thank you

0 likes
8 replies
mtdesigners's avatar

Is this correct:

$posts = Post::whereHas('user', function (Builder $query) {
            $query->where('approved', true);
        })->get();
Niush's avatar
Niush
Best Answer
Level 50

@mtdesigners Yes that is correct. And to include the user relation as well add it like before using with.

$posts = Post::whereHas('user', function (Builder $query) {
      $query->where('approved', true);
})
->with('user', function (Builder $query) {
      $query->where('approved', true);
})
->latest()
->get();

In latest version of Laravel (v9.16.0), you can make this shorter with:

$posts = Post::withWhereHas('user', function (Builder $query) {
      $query->where('approved', true);
})
->latest()
->get();
1 like
mtdesigners's avatar

@Niush Thank you. 😊 I can't find that withWhereHas. is it on Laravel docs?

mtdesigners's avatar

@sr57 I don't think we can close threads here. if it's possible I don't know how!

mtdesigners's avatar

@sr57 Thanks. I didn't know setting the best answer means closing the thread, and didn't know about that guideline post. Appreciate it 😊

Please or to participate in this conversation.