mdev11's avatar
Level 1

Get x number or records with total records count

I have the following Eloquent:

$latestFivePosts = Post::query()
    ->join('users AS u', 'u.id', 'posts.user_id')
    ->where('user_id', auth()->id())
    ->latest('posts.created_at')
    ->take(5)
    ->get();

I want to get the total count of posts for that user too. I know COUNT is an aggregate function and returns one query.

Is there an alternative way to run the same query with some modifications?

$posts = Post::query()
    ->join('users AS u', 'u.id', 'posts.user_id')
    ->where('user_id', auth()->id())
    ->count();
0 likes
2 replies
Snapey's avatar

You could also use the paginator, and read the total number of records off the paginator.

$latestFivePosts = auth()->user()->posts()->latest()->paginate(5);

$totalPosts = $latestFivePosts->total();

Please or to participate in this conversation.