amitsolanki24_'s avatar

How can I take only 10 count from a Eloquent Query Response.

Hello everyone, I'm stuck in below code. Could you please help me to figure out the solution?

        $notifications_count= Notification::where('to_userid', $user_id)
            ->where('is_read', 0)
            ->has('user')
            ->take(10)
            ->count();

I think take() is not working with count(). so how can I do this?

0 likes
10 replies
Snapey's avatar

you are not fetching any records so take() is irrelevant

Also, has('user') is also redundant as you already filter to matching user_id

1 like
amitsolanki24_'s avatar

@Snapey okay, so how can I do that.

And I'm using has('user') because when I display notifications and any notification author is set to deactivate than user is unable to see notification author name.

Shivamyadav's avatar

Just simply remove count with get(). ''' $notifications_count= Notification::where('to_userid', $user_id) ->where('is_read', 0) ->has('user') ->take(10) ->get(); '''

1 like
Snapey's avatar

okay, so how can I do that.

Do what? Your intention is unclear. If you want count only then leave out take()

1 like
amitsolanki24_'s avatar

@Snapey I want to display maximum 10 notifications count. Suppose user_id = 2678 has total 19 notifications so I want to display only 10 notifications count.

amitsolanki24_'s avatar

@Snapey I have solved this issue by using min()

min($notifications_count, 10);

It's giving me correct data that I want.

@snapey Do you know how can I do this with eloquent query builder?

Snapey's avatar

@amitsolanki24_ I would do this in blade

$notifications_count= Notification::where('to_userid', $user_id)
            ->where('is_read', 0)
            ->has('user')
            ->count();

in blade

{{ $notifications_count >10 ? '10+' : $notifications_count }}
1 like

Please or to participate in this conversation.