Laravel 6 Event Listener Mailable Queue unable to access

亡梦爱人 提交于 2021-02-11 12:09:46

问题


Environment:
php: 7.4.2
laravel: 6.15.0

Scenario: Upon user registration, event(new NewUserHasRegisteredEvent($user)); is triggered.

In my EventServiceProvider.php

protected $listen = [
    NewUserHasRegisteredEvent::class => [
        \App\Listeners\WelcomeNewUserListener::class,
    ],
];

My NewUserHasRegisteredEvent.php

<?php

namespace App\Events;

use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewUserHasRegisteredEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

My WelcomeNewUserListener.php Note that it implements ShouldQueue

<?php

namespace App\Listeners;

use App\Events\NewUserHasRegisteredEvent;
use App\Mail\WelcomeUserMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;

class WelcomeNewUserListener implements ShouldQueue
{
    public function __construct()
    {
        //
    }

    public function handle(NewUserHasRegisteredEvent $event)
    {
        Mail::to($event->user->email)->send(new WelcomeUserMail($event->user));
    }
}

My WelcomeUserMail.php

<?php

namespace App\Mail;

use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class WelcomeUserMail extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->markdown('emails/new-welcome')
            ->with('user', $this->user);
    }
}

My new-welcome.blade.php

@component('mail::message')
Hello {{ $user->name ?? 'name' }}, ...
@endcomponent

Issue: When the user receives the registration email, the $user->name is not defined hence i'm using ?? operator. Weird thing is when I remove the ShouldQueue from the WelcomeNewUserListener.php then the $user->name works perfectly fine.

Please suggest. I want to use queue via event/listeners way.

来源:https://stackoverflow.com/questions/60214279/laravel-6-event-listener-mailable-queue-unable-to-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!