Undefined variable in the Variable when trying to send email

Asked

Viewed 130 times

0

I need to send email to more than one person, for that I created a repeat structure for, but I’m getting that my variable is undefined.

I tried something like:

public function avisarAnjos(Request $request)
{
        $usuariosAnjos = User::select('email')
               ->where('usuario_anjo', 1)
               ->get();


        $data = array(
            'lat' => $request->lat,
            'lng' => $request->lng,
            'foto' => $request->foto
        );

        for($i=0;$i < count($usuariosAnjos); $i++){
            Mail::send('email', $data, function ($message){
            $message->from('[email protected]', 'teste!');
            $message->to($usuariosAnjos[$i]);
        });
    }
    return response()->json("Email enviado com sucesso", 201);
}

If I put one return response()->json($usuariosAnjos, 201); I have a array with two emails, I don’t understand why you say this variable is undefined.

  • 1

    This is because $usuariosAnjos is not in the scope of the anonymity function you use to send the email, after Function($message) put a use($usuariosAnjos) and it should work, getting Function($message) use ($usuariosAnjos){}

  • Everton is right, but, you also need to always put the line that the error happened, it is complicated to only see the code and guess that it is the lack of a variable. Something else instead of using for utilise foreach.

1 answer

0

To use a function that is outside the scope use "use" there in Mail::send();

public function avisarAnjos(Request $request)
    {
            $usuariosAnjos = User::select('email')
                   ->where('usuario_anjo', 1)
                   ->get();


            $data = array(
                'lat' => $request->lat,
                'lng' => $request->lng,
                'foto' => $request->foto
            );

            for($i=0;$i < count($usuariosAnjos); $i++){
                Mail::send('email', $data, function ($message) use $usuariosAnjos{
                $message->from('[email protected]', 'teste!');
                $message->to($usuariosAnjos[$i]);
            });
        }
        return response()->json("Email enviado com sucesso", 201);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.