Error passing data to the Mail method :: send laravel


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('', '')->join('users','','=','vacations.user_id')
                ->where(['' => $request->vacation_id])
    Mail::send("correo.aprobado", $dat, function($message) use ($dat,$name){

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

2 answers


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){
       $message->to($dat[0]->email, $dat[0]->name)

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

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('', '')->join('users','','=','vacations.user_id')
                ->where(['' => $request->vacation_id])
    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