#Why do I get `$to` must not be defined on class?

9 messages · Page 1 of 1 (latest)

slow sierra
#
[2023-04-12 21:58:37] local.ERROR: Type of App\Mail\RedFlagMessageMail::$to must not be defined (as in class Illuminate\Mail\Mailable) {"userId":2,"exception":"[object] (Symfony\\Component\\ErrorHandler\\Error\\FatalError(code: 0): Type of App\\Mail\\RedFlagMessageMail::$to must not be defined (as in class Illuminate\\Mail\\Mailable) at C:\\laragon\\www\\_WORK\\FROSTEAM\\n90\\app\\Mail\\RedFlagMessageMail.php:12)
[stacktrace]
#0 {main}
"} 

My class

class RedFlagMessageMail extends Mailable
{
    use Queueable, SerializesModels;

    public string|array $to;
    public string $subject;

    /**
     * Create a new message instance.
     * @param string|array $to;
     * @param string|null $subject
     * 
     * @return void
     */
    public function __construct(string|array $to, ?string $subject = null)
    {
        $this->to = $to;
        $this->subject = $subject;
    }

Called by Mail::to(auth()->user()->email)->send(new RedFlagMessageMail(auth()->user()->email));

distant rose
#

Because the $to property in the parent class isn't typed

slow sierra
distant rose
#

The parent class, Mailable, defines public $to = [];. You can't override the type of a property.

slow sierra
#

Does this mean i should avoid adding $to on the constructor

distant rose
#

This has nothing to do with your constructor

gritty umbra
#

@slow sierra Why are you trying to set a $to inside the class at all? You’re meant to specify the recipient when sending; not in the mailable itself:

Mail:to('someone@example.com', new RedFlagMessage());
#

Mailable classes are meant to be “blueprints” of emails.

distant rose
#

You probably shouldn't be passing $to in the constructor, but for different reasons