Search code examples
laravelemailqueuejobs

Laravel: Send email using queue and jobs


I want to send email using laravel queue. I follow tutorial from this site https://blog.mailtrap.io/laravel-mail-queue/ . It is work (email can be send using job and queue).

But i want to include value in the email. Below are the code that i modify to send the value.

I thought $details array will carry the value and pass to the email template. But when i run, the job is failed. Is there any way that i could improve?

PController.php

$details = array(
            'email' => '[email protected]',
            'fruitname' => 'watermelon',
            'fruitid' => 'F001'
        );

dispatch(new SendEmail($details))->delay(Carbon::now()->addSeconds(10));

Mailable Class: SendEmail.php

protected $details;

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

public function handle()
    {
        $email = new MailFruit();
        Mail::to($this->details['email'])->send($email);
    }

MailFruit.php

protected $details;

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

public function build()
    {
        return $this->from('[email protected]')
                    ->subject('New Fruit')
                    ->view('emails/email_fruit_template')
                    ->with('details', $this->details);
    }

email_fruit_template.blade.php

@component('mail::message')

New Fruit Details

Fruit ID: {{ $details['fruitid'] }}
Fruit Name: {{ $details['fruitname'] }}

Fruit Company
@endcomponent

Any help will be grateful. Thank you.

Edit: This one appear on cmd.

$php artisan queue:work
[2020-08-12 14:36:22][58] Processing: App\Jobs\SendEmail
[2020-08-12 14:36:23][58] Failed:     App\Jobs\SendEmail

Solution

  • Pass details array in the new instance of Mailfruit.

    
    public function handle()
        {
            $email = new MailFruit($this->details);
            Mail::to($this->details['email'])->send($email);
        }