Laravel - Notifications - Accessing The Notifications
Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The Illuminate\Notifications\Notifiable
trait, which is included on Laravel's default App\Models\User
model, includes a notifications
Eloquent relationship that returns the notifications for the entity. To fetch notifications, you may access this method like any other Eloquent relationship. By default, notifications will be sorted by the created_at
timestamp with the most recent notifications at the beginning of the collection:
$user = App\Models\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}
If you want to retrieve only the "unread" notifications, you may use the unreadNotifications
relationship. Again, these notifications will be sorted by the created_at
timestamp with the most recent notifications at the beginning of the collection:
$user = App\Models\User::find(1);
foreach ($user->unreadNotifications as $notification) {
echo $notification->type;
}
To access your notifications from your JavaScript client, you should define a notification controller for your application which returns the notifications for a notifiable entity, such as the current user. You may then make an HTTP request to that controller's URL from your JavaScript client.