Sendmail Subject in Laravel 5.1

2019-09-09 14:27发布

问题:

I want send email with subject using variable , this is code

public function sendmail(Request $request)
{
    $data = [
        'subject'   =>  $request->input('subject'),
        'name'  => $request->input('name'),
        'phone' =>  $request->input('phone'),
        'email' =>  $request->input('email')
    ];
    Mail::send('mail.sendmail' , $data, function($msg){
        $msg->from('mygmail.com', 'Avil');
        $msg->to('mygmail@gmail.com', 'Avil')->subject('Welcome to Laravel 5.1');
    });
    return redirect()->route('contact.index');
}

I wanna subject not "Welcome to Laravel 5.1", Subject is

public function sendmail(Request $request)
{
    $data = [
        'subject'   =>  $request->input('subject'),
        'name'  => $request->input('name'),
        'phone' =>  $request->input('phone'),
        'email' =>  $request->input('email')
    ];
    Mail::send('mail.sendmail' , $data, function($msg){
        $msg->from('mygmail@gmail.com', 'Hung Nguyen');
        $msg->to('mygmail@gmail.com', 'Hung Manh')->subject($data['subject']);
    });
    return redirect()->route('contact.index');
}

When I running display error :

Undefined variable: data

Please help me. Thank you so much

回答1:

You have to pass along $data to the callback in your send method. Refer the line where Mail façade is used.

public function sendmail(Request $request)
{
    $data = [
        'subject'   =>  $request->input('subject'),
        'name'  => $request->input('name'),
        'phone' =>  $request->input('phone'),
        'email' =>  $request->input('email')
    ];
    Mail::send('mail.sendmail' , function($msg) use($data){
        $msg->from('mygmail@gmail.com', 'Hung Nguyen');
        $msg->to('mygmail@gmail.com', 'Hung Manh')->subject($data['subject']);
});
    return redirect()->route('contact.index');
}