I have two models User
and Posts
I want to check if some user
has posts
with given title
.
$user = User::find($userId);
$posts = $user->posts;
$postsWithGivenTitle = $posts->where('title','=',$title);
$postCount = $postsWithGivenTitle->count();
I suppose this above should work but I need to go above this and do it efficiently. So I got this and it's working but still not sure is it the right way to do it.
$user = User::find($userId)->withCount(['posts' => function ($q) use ($title) {
$q->where('title','=',$title);
}])->first();
and then to check the count:
if ($user->posts_count > 0) {
//do something
}
What's confusing me, and looks ugly, is using the methods find()
and first()
in the same query. So hopefully I'm missing something simple here and overthinking it.
Thanks
As you can see in the docs: https://laravel.com/docs/5.3/eloquent-relationships
You can acheive what you want like this:
$user = User::withCount(['posts' => function($q){....}])->find($id)