Nicolas Decroos Nicolas Decroos - 5 months ago 36
PHP Question

Undefined variable - laravel emailing

I'm trying to send an email using laravel. This worked for serveral functions but with this one I'm getting a weird error.

here's the code I'm using

$offerte = DB::table('offertes')
->select('*')
->where('id', '=', $offerte_id)
->get();

Mail::send('emails.offerte_reactie', ['offerte' => $offerte, 'user' => $user, 'message_text' => $message_text], function ($message) use ($user)
{
$message->from($user->email, 'Foodtruckbestellen.be');
$message->to($offerte->email);
$message->subject('Reactie offerte Foodtruckbestellen.be');
});


However when I want to send the mail I get the error


Undefined variable: offerte


The line $message->to($offerte->email); is indeed underlined in red in PHPSTORM and I don't use the variable in the email. so I know for sure that's where my error is I just can't find a fix for it.

Answer

You need to pass the $offerte variable to closure as it's not defined within the closure scope.

Just use the $offertevariable as you do with the $user.

Mail::send('emails.offerte_reactie', ['offerte' => $offerte, 'user' => $user, 'message_text' => $message_text], function ($message) use ($user, $offerte)
{
    $message->from($user->email, 'Foodtruckbestellen.be');
    $message->to($offerte->email);
    $message->subject('Reactie offerte Foodtruckbestellen.be');
});

Furthermore, if I were you, I'd use compact for the array that you pass to the send function's second argument to write more clean code.

Mail::send('emails.offerte_reactie', compact('offerte', 'user', 'message_text'), function ($message) use ($user, $offerte)
{
    $message->from($user->email, 'Foodtruckbestellen.be');
    $message->to($offerte->email);
    $message->subject('Reactie offerte Foodtruckbestellen.be');
});
Comments