phplaravellaravel-notification

How to call custom made function using via parameter in laravel notification?


devs,I am using laravel 8 I create a notification inside that I made my own funciton toTwilio mention below code.

Problem: how can I call that function. I include in return parameter of via() function but it shows me "driver [twilio] not supported.". I do not register anything anywhere. and I tried to change the name of function still showing error "driver[<fun_name>] not supported.


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class DepartmentNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['toTwilio'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {

        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    public function toTwilio($notifiable)
    {
        echo "twilio hit";
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Solution

  • Read the official documentation about custom notification channels here: https://laravel.com/docs/8.x/notifications#custom-channels.

    First of all You should create a TwilioChannel class to call toTwilio method:

    
    <?php
    
    namespace App\Channels;
    
    use Illuminate\Notifications\Notification;
    
    class TwiolioChannel
    {
        public function send($notifiable, Notification $notification)
        {
            $message = $notification->toTwilio($notifiable);
    
            // Send notification to the $notifiable instance...
        }
    }
    

    After creating Channel class change notification via method like this:

    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }