laravellaravel-8laravel-queuelaravel-mail

Getting undefined property error exception when changing mail::send to mail::queue in laravel 8


Here is code that works:

Mail::to($emails)->send(new ExceptionOccurred($e));

And then I change it to:

Mail::to($emails)->queue(new ExceptionOccurred($e));

When I do I get the error:

ErrorException: Undefined property: App\Mail\ExceptionOccurred::$content in C:\inetpub\wwwroot\laravel\app\Mail\ExceptionOccurred.php:33

This is ExceptionOccurred.php:

namespace App\Mail;

use Illuminate\Bus\Queueable;
// use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ExceptionOccurred extends Mailable
{
    use Queueable, SerializesModels;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('mail.ExceptionOccurred')
            ->subject('Exception on live instance')
            ->with('content', $this->content);
    }
}

This is the relevant portion of the exception handler:

if ( $exception instanceof Exception ) {
    $e = FlattenException::create($exception);
} else {
    $e = $exception;
}

$emails = json_decode( env('MAINTAINER_EMAILS') );

if (app()->environment('production') || app()->environment('testing') ) {
    Mail::to($emails)->send(new ExceptionOccurred($e));
}

To re-iterate, Mail::send() works, but Mail::queue() does not. I believe the queue is set up correctly.


Solution

  • You have to define the content attribute before the construct, like this:

    namespace App\Mail;
    
    use Illuminate\Bus\Queueable;
    // use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Mail\Mailable;
    use Illuminate\Queue\SerializesModels;
    
    class ExceptionOccurred extends Mailable
    {
        use Queueable, SerializesModels;
     
        public $content;
    
        /**
         * Create a new message instance.
         *
         * @return void
         */
        public function __construct($content)
        {
            $this->content = $content;
        }
    
        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
            return $this->markdown('mail.ExceptionOccurred')
                ->subject('Exception on live instance')
                ->with('content', $this->content);
        }
    }
    

    Reference: https://laravel.com/docs/8.x/mail#view-data