Error passing data to the Mail method :: send laravel

1

I want to send a confirmation email to the user who requested the service, but when I try to pass the email and name the class to send mail, I get the following error:

Type error: Argument 2 passed to Illuminate\Mail\Mailer::send() must be of the type array, object given

The method I am using to send the mail to the user is the following:

$dat =  \DB::table('vacations')->select('users.email', 'users.name')->join('users','users.id','=','vacations.user_id')
                ->where(['vacations.id' => $request->vacation_id])
                ->get();
    $name[]=$dat[0]->name;
    //dd($dat[0]->email,$name);
    Mail::send("correo.aprobado", $dat, function($message) use ($dat,$name){
       $message->to(['email'=>$dat[0]],['name'=>$dat[0]])
               ->subject("enhorabuena");
    });

the output of the variable $ dat is this:

Collection {#265 ▼
#items: array:1 [▼
    0 => {#256 ▼
      +"email": "[email protected]"
      +"name": "user"
    }
  ]
}

Thank you very much for your attention.

    
asked by Peisou 22.08.2018 в 12:39
source

2 answers

2

The error says that you are sending an object, and if you realize, your variable $dat is an object of the class Collection , to convert your collection to array just send it as $dat->toArray() , it would be of the following way:

Mail::send("correo.aprobado", $dat->toArray(), function($message) use ($dat,$name){
       dd($dat[0]->email);
       $message->to($dat[0]->email, $dat[0]->name)
               ->subject("enhorabuena");
    });

It is important to know the differences between an array and a Laravel collection, maybe when you did this: $dat[0]->name gave you the allusion that it is an array but the operator -> is to access properties of an object, for when you convert it to an array, to access the property name it would be like this $dat[0]['name'] .

    
answered by 22.08.2018 / 15:37
source
0

I publish an answer because with so much comment and so, it is a bit confusing:

In the end the solution comes from what Aaron said, to pass the object to an array, the problem was that the Mail method did not interpret it correctly.

Keeping the code that way:

$dat =  \DB::table('vacations')->select('users.email', 'users.name')->join('users','users.id','=','vacations.user_id')
                ->where(['vacations.id' => $request->vacation_id])
                ->get();
    Mail::send("correo.aprobado", $dat->toArray(), function($message) use ($dat){
        $message->to($dat[0]->email , $dat[0]->name)
                ->subject("Respuesta a su solicitud");
    });

Thank you very much Aaron for your contributions.

    
answered by 22.08.2018 в 17:11