Laravel: customize or extend notifications - database model

前端 未结 5 1403
我在风中等你
我在风中等你 2020-12-03 08:11

IMHO, the current Database channel for saving notifications in Laravel is really bad design:

  • You can\'t use foreign key cascades on items for cleaning up noti
5条回答
  •  甜味超标
    2020-12-03 08:57

    To create a custom Notification Channel:

    First, create a Class in App\Notifications for example:

    toDatabase($notifiable);
    
        return $notifiable->routeNotificationFor('database')->create([
            'id' => $notification->id,
    
            //customize here
            'answer_id' => $data['answer_id'], //<-- comes from toDatabase() Method below
            'user_id'=> \Auth::user()->id,
    
            'type' => get_class($notification),
            'data' => $data,
            'read_at' => null,
        ]);
      }
    
    }
    

    Second, use this channel in the via method in the Notification class:

    answer = $answer;
      }
    
      public function via($notifiable)
      {
        return [CustomDbChannel::class]; //<-- important custom Channel defined here
      }
    
      public function toDatabase($notifiable)
      {
        return [
          'type' => 'some data',
          'title' => 'other data',
          'url' => 'other data',
          'answer_id' => $this->answer->id //<-- send the id here
        ];
      }
    }
    

提交回复
热议问题