Undefined Variable Inside Mail::send in Laravel 5

2019-08-06 05:41发布

public function postAcceptedSign($md5)
{
    $notif = CustomerOrder::where('sign_link', '=', $md5)->get();

     Mail::send('emails.signed-notif', ['order_num' => $notif[0]->order_number], function ($m) {
        $m->to('mis@qdf-phils.com', '')->subject('Customer Order '.$notif[0]->order_number.' is now signed');
    });

    Session::flash('alert-success', 'Order Signed.');

    return Redirect::to('home');
}

I am getting Undefined variable: notif which points to this

Mail::send('emails.signed-notif', ['order_num' => $notif[0]->order_number], function ($m) {
   $m->to('mis@qdf-phils.com', '')->subject('Customer Order '.$notif[0]->order_number.' is now signed');
});

Why I get undefined variable in $notif[0] where as you can see my variable is already defined above? Is this because the starting Mail::send is a separate block that It can't see other variables?

1条回答
Lonely孤独者°
2楼-- · 2019-08-06 06:07

The block of the closure (your function that sends the email) has not visibility of the outside block's scope.

So, if you want to access the variable from inside the closure, you have to explicitly pass it to the closure with the use keyword; like this:

Mail::send( 'emails.signed-notif', 
            ['order_num' => $notif[0]->order_number],
            function($m) use ($notif) /* here you're passing the variable */
            {
                $m->to('mis@qdf-phils.com', '')->subject('Customer Order'.$notif[0]->order_number.' is now signed');
            } );

For more info on anonymous functions and closures check here

查看更多
登录 后发表回答