Level 75
$result = User::withCount('posts')->first();
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models
Add other where condition, you have user_id column in users table?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a query using join but i don't want to use join and want to get same result by using relationship
$result = User::where('id', 1)
->where('deleted', false)
->leftJoin('posts', 'posts.user_id', '=', 'users.id')
->groupBy(['users.id'])
->selectRaw('users.*, count(posts.id) as post_count')
->orderBy('users.id', 'DESC')
->first();
dd($result);
In User.php
public function posts()
{
return $this->hasMany(\App\Post::class);
}
and all posts belongs to user.
can you help me how to get same results without using join. Thanks
$result = User::withCount('posts')->first();
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models
Add other where condition, you have user_id column in users table?
Please or to participate in this conversation.