0
votes

I am trying to send notification (email) using Notifiable trait (notify()) method from a Non User Eloquent Model

Driver Model

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Driver extends Authenticatable
{
  use Notifiable;
}

And to send notification I am using

  $driver->notify(new \App\Notifications\Driver\DriverAlloted($booking));

Where $driver is a eloquent model instance (app\Driver.php) and \App\Notifications\Driver\DriverAlloted is the Notification;

If I replace driver with any user (App\User) it works, how can I get it working for App\Driver

1
Seems you copied the User class, why driver extending Authenticatable ?sadaiMudiNaadhar
Whats your laravel version?sadaiMudiNaadhar
Are you getting an error? What channels are you trying to send the notification with?Rwd

1 Answers

2
votes

When a notification asks for the mail channel, Laravel calls this code from the Illuminate\Notifications\RoutesNotifications trait (extended by Illuminate\Notifications\Notifiable trait)

/**
     * Get the notification routing information for the given driver.
     *
     * @param  string  $driver
     * @param  \Illuminate\Notifications\Notification|null  $notification
     * @return mixed
     */
    public function routeNotificationFor($driver, $notification = null)
    {
        if (method_exists($this, $method = 'routeNotificationFor'.Str::studly($driver))) {
            return $this->{$method}($notification);
        }

        switch ($driver) {
            case 'database':
                return $this->notifications();
            case 'mail':
                return $this->email;
        }
    }

Therefore you have 2 ways to solve it:

  • Your Driver model needs to have an email attribute which will be the route to reach with the mail.

  • Define a routeNotificationForMail method in your model which will computes the route on a custom way

/**
 * @param  \Illuminate\Notifications\Notification|null  $notification
 * @return string
 */
public function routeNotificationForMail($notification)
{
    return $this->address;
}