How do I select between multiple notification channels?
Hi folks
Fairly new to Laravel and slowly building a team invite system. I've read up and Googled as much as I can on how to use Laravel Notifications, but I'm stuck on how to select between multiple notifcation channels (most likely based on user preference setting).
Here's my notification:
namespace App\Notifications\Frontend\Team;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
/**
* Class TeamInvitation.
*/
class TeamInvitation extends Notification
{
use Queueable;
/**
* @var
*/
protected $team_invite;
/**
* TeamInvitation constructor.
*
* @param $team_invite
*/
public function __construct($team_invite)
{
$this->team_invite = $team_invite;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*/
public function via($notifiable)
{
return ['database', 'mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage())
->subject(app_name().': '.__('exceptions.frontend.auth.confirmation.confirm'))
->line(__('strings.emails.auth.thank_you_for_using_app'));
}
/**
* @param $notifiable
* @return mixed
*/
public function toDatabase($notifiable)
{
return $this->team_invite->toArray();
}
}
and in my controller I have
$user->notify(new TeamInvitation($team_invite));
Currently works in the sense that notification is created in my database table and and email notification is sense. How would I select which channel to use in my controller?
if it's going to be via user settings, I suggest saving those settings to the user model (or another related model).
After that you could do something like this:
public function via($notifiable)
{
return $notifiable->settings['channels'];
// return ['database', 'mail'];
}
Where settings would be a related model, in which the users can save which channels they would like to be notified on. The controller code would stay the same as you have it now.