Undefined Variable Inside Mail::send in Laravel 5

2019-08-06 05:50发布

问题:

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:

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