Error sending emails with user data with Laravel

0

I get the following error when trying to send an email with laravel

  

Type error: Argument 1 passed to App \ Mail \ AnalystMonth :: __ construct ()   must be an instance of App \ Mail \ DataUser, instance of   Illuminate \ Database \ Eloquent \ Collection given, called in   C: \ wamp \ www \ intranet \ intranet \ app \ Http \ Controllers \ AnalystController.php   online 37

My Mailer class

class AnalystMonth extends Mailable
{
    use Queueable, SerializesModels;

    public $dataUser;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(DataUser $dataUser)
    {
        $this->dataUser = $dataUser;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('mails.analystMonth');
    }
}

My controller function to send the email

public function choiceAnalyst(Request $request){

   $file = $request->file('document');
   $userSelect = $request->input('user');
   $data = User::where('id', '=', $userSelect)->get();

   \Mail::to('[email protected]')->send(new AnalystMonth($data));

}

How can I solve the error ?, I know that the error is in the part that I want to load the data to see them, because if I remove those lines of code, the mail arrives without problem

    
asked by Edwin Aquino 23.05.2018 в 20:29
source

1 answer

1

Since we arrived at what was the inconvenience in the comments I added it as an answer.

The error in question is:

  

Type error: Argument 1 passed to App \ Mail \ AnalystMonth :: __ construct ()   must be an instance of App \ Mail \ DataUser, instance of   Illuminate \ Database \ Eloquent \ Collection given, called in   C: \ wamp \ www \ intranet \ intranet \ app \ Http \ Controllers \ AnalystController.php   online 37

That "translated" says something like the constructor of the AnalystMonth class expects a DataUser class object (I think you finally changed it to User) but it is receiving a Collection.

The solution would be to replace the ->get() with a ->first() at the moment the user brings it, since get() brings a collection of users, in this case a collection with a single user inside and first() returns the user object directly.

$data = User::where('id', '=', $userSelect)->first(); //cambio de get() por first()

Greetings!

    
answered by 23.05.2018 / 21:29
source