首页 > 解决方案 > How to customize subject email using Laravel 5.5

问题描述

I have an event that triggers a listener as soon as a vehicle is created on the system.

This is my event:

class VehicleCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    private $vehicle;

    public function __construct(Vehicle $vehicle)
    {
        $this->vehicle = $vehicle;
    }

    public function getVehicle()
    {
        return $this->vehicle;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

This is my listener:

class SendSchedulingConfirmationListener implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(VehicleCreated $event)
    {
        $vehicle = $event->getVehicle();
        $lead = $vehicle->lead;
        Mail::to($lead->email)
            ->queue(new SchedulingConfirmation($vehicle, $lead));
    }
}

I used the artisan command to create the email:

php artisan make:mail SchedulingConfirmation --markdown=emails.leads.scheduling.confirmation

I'm having trouble customizing the subject of the email currently my class looks like this:

class SchedulingConfirmation extends Mailable
{
    use Queueable, SerializesModels;

    public $vehicle;
    public $lead;

    public function __construct(Vehicle $vehicle, Lead $lead)
    {
        $this->vehicle = $vehicle;
        $this->lead = $lead;
    }

    public function build()
    {
        return $this
            ->subject('This is my subject')
            ->markdown('emails.leads.scheduling.confirmation');
    }
}

When I fire the email it arrives in mailtrap with the subject of Scheduling Confirmation

标签: laravellaravel-5

解决方案


您可以在新建邮件时传递主题:

$subject = 'truly awesome subject line';

Mail::to($lead->email)
        ->queue(new SchedulingConfirmation($vehicle, $lead, $subject));

所以在你的类中,只需$subject在构造函数中添加作为参数:

class SchedulingConfirmation extends Mailable
{
    use Queueable, SerializesModels;

    public $vehicle;
    public $lead;

    public function __construct(Vehicle $vehicle, Lead $lead, $subject)
    {
        $this->vehicle = $vehicle;
        $this->lead = $lead;
        $this->subject = $subject
    }

    public function build()
    {
        return $this
            ->subject($this->subject)
            ->markdown('emails.leads.scheduling.confirmation');
    }
}

推荐阅读