Skip to content

Non-initialized public typed properties on mailables throw an exception #49812

Closed
@j3j5

Description

@j3j5

Laravel Version

10.42.0

PHP Version

8.2.7

Database Driver & Version

No response

Description

When using Mailables, all public properties are made available to the view, that's expected behavior. But if the mailable contains a public (typed) variable that hasn't been initialized, the buildViewData() method throws an exception
Typed property App\Mail\YourClass::$variable must not be accessed before initialization.

I think there should be a check on buildViewData() to make sure typed variables are initialized before being passed to the view.

Steps To Reproduce

php artisan make:mail OrderShipped

<?php

namespace App\Mail;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    public User $user;

    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

Then, try to send this mailable, from tinker:

$mail = $mail = new App\Mail\OrderShipped();
Mail::to("mail@example.org")->send($mail);

It will throw an exception

Error Typed property App\Mail\OrderShipped::$user must not be accessed before initialization.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions