es915
es915

Reputation: 155

how do i count the number of unread notification in laravel that have a specific value

I am trying to count how many unread notifications i have in laravel that does not have a name value of the user that is logged in.

so far i have managed to do the following where i get the number of all the unread notifications:

auth()->user()->unreadNotifications->count()

but i want to only count the ones that have a name value that is not equal to the name of the user that is logged in

i have come up with something like this but its not working and i am not sure how to do not equal to rather than equal to:

  $numberofnotifications = auth()->user()->unreadNotifications::where('name', Auth::user()->name)->count();

Upvotes: 0

Views: 4854

Answers (2)

Abbas Arif
Abbas Arif

Reputation: 390

If you are using MySQL 5.7+ or MariaDB 10.2+ you can take advantage of Json Search.

auth()->user()->unreadNotifications()->where('data->name', '<>', auth()->user()->name)->count();

For all unread notification you should count like below instead of auth()->user()->unreadNotifications->count().

Auth::user()->unreadNotifications()->count()

Your method will load all the notifications and then count will be performed in php when you can simply get the count with single query.

Upvotes: 2

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2355

I won't test it but if you have a look at vendor/laravel/framework/src/Illuminate/Notifications/DatabaseNotification.php you'll notice a method called newCollection. So it stands to reason this should work in the context of your requirements:

$numberofnotifications = auth()->user()->unreadNotifications::newCollection()->where('name', '<>', Auth::user()->name)->count();

Upvotes: -1

Related Questions