create() must be of the type array (mailtrap error in laravel)

627 views Asked by At

I am building a complaint management system and I configure mailtrap in laravel to send mails. What I want is when the user adds a new complaint then there will be automatically sent a 'new complaint' email to the admin. I wrote a simple code in the add new complaint function in the controller but when I run the app there is an error that I don't understand.

TypeError Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in C:\xampp\htdocs\Complain-Management-System\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23

This is my create function:

public function create(Request $data)
{
    //  dd($data['user_id']);

    $data->validate([
        'type'          =>  'required',
        'station'       =>  'required',
        'description'   =>  'required|min:20|max:1000',
    ]);
    
    Complaint::create([
        'type'          => $data['type'],
        'station'       => $data['station'],
        'description'   => $data['description'],
        'comment'       => $data['comment'],
        'status'        => $data['status'],
        'user_id'       => $data['user_id']
    ]);

    $complaint = Complaint::create($data);
    Mail::send('emails.test', $complaint->toArray(),function($message) {
        $message->to('[email protected]', 'Test Mail')
        ->subject('Complaint Created');
    });
    
    return redirect()->route('all-complaints');
}

And this is the route:

Route::post('complaints', [App\Http\Controllers\ComplaintController::class, 'create'])->name('new-complaint')->middleware('loggedIn');
1

There are 1 answers

0
lagbox On

If Complaint is an Eloquent Model you need to pass an array to create not a Request object, $data is a Request. Not sure why you are trying to create 2 complaints (I assume from the same data).

If you need the newly created Complaint model just assign it to $complaint after you create it with the array:

$complaint = Complaint::create([
    'type'          => $data['type'],
    'station'       => $data['station'],
    'description'   => $data['description'],
    'comment'       => $data['comment'],
    'status'        => $data['status'],
    'user_id'       => $data['user_id']
]);

No need for the other call to Complaint::create you have.