问题
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