Search code examples
laraveleloquenteloquent-relationship

Get associated user of DatabaseNotification


I'm using DatabaseNotification with columns : type, notifiable_type and notifiable_id. I'd like to get all notification with that type and notifiable_type and I know how to do with where clause.

$notificationList = DatabaseNotification::where('type','App\Notifications\NewBulletinNotification')
            ->get();

I know that all notifications that I want, have notifiable_id that it's a user ID.

How can I get user data with each notification?

I don't know how to add relationship function to DatabaseNotification. expected query example:

$notificationList = DatabaseNotification::where('type','App\Notifications\NewBulletinNotification')
            ->with('users') // or something else with user data for each notification.
            ->get();

thanks!!


Solution

  • You can use notifiable() relation of DatabaseNotification Model.

    $notificationList = DatabaseNotification::where('type','App\Notifications\NewBulletinNotification')
                ->with('notifiable')
                ->get();
    

    API ref: https://laravel.com/api/10.x/Illuminate/Notifications/DatabaseNotification.html#method_notifiable