Is this correct:
$posts = Post::whereHas('user', function (Builder $query) {
$query->where('approved', true);
})->get();
Be part of JetBrains PHPverse 2026 on June 9 β a free online event bringing PHP devs worldwide together.
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
@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();
Please or to participate in this conversation.