Ad

Laravel Multiple Notifications Type

- 1 answer

I want to have multiple notifications type in my web app. I've already done pretty fine notifying a user of a particular thing that occured; it works. What I want to do now is creating another notification type. As Laravel uses the same notifications table for all notifications as I've read here I created another Notification class with the php artisan make:notification command. After setting it up, when triggered it works fine too: it is well recorded in the notifications database table with it specific 'type' mentioned in the notificationstype column. Now the intended user should be able to receive both notifications.

My issue is how do I manage to get that specific notification shown to the user. With the first notification class implemented, all was working fine: the user get his notifications. With now two notifications type, whenever I try to display all notifications with a @foreach(auth()->user()->notifications as $notification) in the blade view like I was doing, I'm getting an error Undefined index: EtudiantsChoixTheme with EtudiantsChoixTheme being data I send to the user:


        $EtudiantsChoixTheme = [
            'id' => $idData,
                 ...
            'theme' => $themeData
        ];

        \Notification::send($user, new StudentChoosedThemeNotification($EtudiantsChoixTheme));

StudentChoosedThemeNotification being the first Notification class I've implemented. This error occurs only when I want to display notifications of a user which has received (user id in the notifiable_id field) the two Notification types. I tried what I've read here : $user->notifications->filter(function($e) { $e->type == 'NewNotificationClass'}) but I'm getting an error :syntax error, unexpected '}'... I've also tried to display the notification type with {{$notification->type}} but this is only displayed for the users which has only one type of notification received. When a user receive more than one Notification it seems I can't anymore display those notifications.

How precisely may I retrieve the notification data of a particular notification type for a user in Laravel? Had anyone of you already did something like this? Any help will be very appreciated

Ad

Answer

$notifications = $request
->user()
->notifications
->where('type', 'App\Notifications\CommentCreated')
->all();

https://laravel.com/docs/6.x/collections#available-methods

Ad
source: stackoverflow.com
Ad