jeudi 7 novembre 2019

Laravel Notification with Mailable

In my Laravel application I have a Notification that sends a Mailable when a User is deleted.

The Notification class:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;
use App\Mail\UserDeleted as UserDeletedEmail;

class UserDeleted extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * The user instance being passed to the notification
     *
     * @var User $user
     */
    protected $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new UserDeletedEmail($notifiable, $this->user));
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'user_id' => $this->user['id'],
            'user_username' => $this->user['username'],
            'user_email' => $this->user['email'],
            'user_full_name' => $this->user['full_name'],

        ];
    }
}

In this case $notifiable is an instance of User but soo is $user as this is the user that has been deleted.

The Mailable looks like this:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Spatie\Permission\Models\Role;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;


class UserDeleted extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The order instance.
     *
     * @var User
     */
    public $user;

    /** 
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->to($this->user->email)
            ->subject("{$this->user->full_name} been deleted from the Citibase Intranet")
            ->markdown('mail.user-deleted');
    }
}

The issue is, as they're both instances of User I'm effectively passing the wrong instance in the subject line.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire