Search code examples
phplaravelsmtpgmail

unreachable statement in laravel when executing a function


Am trying to execute a send mail function when a record is stored in the database but am getting unreachable statement

public function store(Request $request)
    {
        $visit = Visit::create($request->all());
        return response()->json($visit);
        $this->sendEmail($request);

    }

This is the send email function

public function sendEmail(Request $request){
        $visit = Visit::create($request->all());
        $host_email = Db::table('users')
            ->where('name', '=', $visit->visitor_host)
            ->value('email');

        $to_name =  $request->input('visitor_name');
        $data = array('name'=> $to_name, "body" => "Test mail");


        Mail::send('mails.mail', $data, function($message) {
            $message->from('[email protected]','cytonn');
            $message->to('[email protected]');
            $message->subject('Visitor coming notification');

        });
    }

Solution

  • From the manual:

    If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

    Change your code to

    $this->sendEmail($request);
    return response()->json($visit);
    

    to execute the mail send before your return.