3

I have been working on notifications and was getting through it pretty quickly unless I felt the need of deleting and relating a notification to a Post, is there any way I can associate a Model to the notifications table? I thought of using the $table property found in the model after creating the notification model.

Edit: Or can I delete a notification when a post is deleted?

Saud Qureshi
  • 1,456
  • 1
  • 19
  • 20

1 Answers1

7

Of course you can. php artisan make:model Notification

Then change the model to extend laravel's default notification model.

    <?php

    namespace App;

    use Illuminate\Notifications\DatabaseNotification;

    class Notification extends DatabaseNotification
    {
        public function users()
        {
            return $this->belongsTo(User::class, 'notifiable_id');
        }
    }

Then you can define your relationship in this notification model.

Alternatively, you can delete the notification using user-post relationship

$post->user->notifications->delete()

Dennis Mwea
  • 339
  • 3
  • 8
  • One and a half year late, but still relevant. Thank you!. – Saud Qureshi Oct 18 '19 at 09:03
  • I would point out that any model can have the Notifiable trait, so while most applications will only use the User for notifications, if another model has the notifiable trait, this could interfere with this function. – Dan S Dec 16 '21 at 17:46
  • In addition, for the latest version of Larvel (8+), remember to namespace it App\Models. – Dan S Dec 16 '21 at 17:47
  • @DanS True, in that case, you just need to change the relationship to the model which has the notifiable trait. – Dennis Mwea Jan 14 '22 at 08:27