Search code examples
phplaravelmailtrap

Offset on value null issue for Mailtrap on Laravel 7


I am using Laravel 7 and PHP 7.4.

I'm using Mailtrap for test emails. I just upgraded my Laravel version to 7.4 and my email has been stopped to work. When I try to send demo email, it gives me an error below

Trying to access array offset on value of type null

The issue is here:

 {{ $mailData['title'] }}

Controller:

class MailController extends Controller {

    public function sendEmail() {
        $email = '[email protected]';

        $mailData = [
            'title' => 'Demo Email',
            'url' => 'https://www.positronx.io'
        ];

        Mail::to($email)->send(new EmailDemo($mailData));

        return response()->json([
            'message' => 'Email has been sent.'
        ], Response::HTTP_OK);
    }

}

MailFile:

class EmailDemo extends Mailable
{
    use Queueable, SerializesModels;
    public $mailData;

    public function __construct()
    { }

    public function build()
    {
        return $this->markdown('email.demoEmail')
            ->with('mailData', $this->mailData);
    }
}

Blade:

@component('mail::message')
     {{ $mailData['title'] }}

    The body of your message.

    @component('mail::button', ['url' => $mailData['url']])
        Button Text
    @endcomponent

    Thanks,<br>
    {{ config('app.name') }}
@endcomponent

Solution

  • You are forgetting to set $mailData in the constructor(), pass it to the constructor and set it to $this->maildata.

    class EmailDemo extends Mailable
    {
        use Queueable, SerializesModels;
        public $mailData;
    
        public function __construct($mailData)
        {
            $this->mailData = $mailData;
        }
    }