Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel "Type error: While Updating Records with PUT/PATCH Methods

Tags:

php

laravel

When i run the update controller it gives me this error, i tried different solution from this same platform with this error but their fix was to update with separated syntax of save($product) like that. I am using Model Store for authentication and saving the data or editing deleting.

"Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in C:\xampp\htdocs\shopping\app\Http\Controllers\ProductController.php on line 138 ◀"

Update Method

 public function update(Request $request, Product $Product){
      $store = Store::where('user_id', Auth::user()->id)->first();
      $updateProduct = $store->product()->save([
         'name'=> $request->input('name'),
         'description' => $request->input('description'),
         'normal_price' => $request->input('normal_price'),
         'sale_price' => $request->input('sale_price'),
         'category_id' => $request->input('category_id'),
     ]);
         return redirect('product')->with('status', 'Product Updated');
 }

View Edit Form

 <form method="post" action="{{route('product.update', $product->id)}}">
                                {{ csrf_field() }}
                                {{ method_field('PUT') }}
like image 224
Hassam Ali Avatar asked Jan 26 '26 15:01

Hassam Ali


2 Answers

When you're using save() Laravel expects model.

Use create() method. Change this:

$updateProduct = $store->product()->save([

To:

$updateProduct = $store->product()->create([

Or do this:

$updateProduct = $store->product()->save(new Product([
    'name'=> $request->input('name'),
    'description' => $request->input('description'),
    'normal_price' => $request->input('normal_price'),
    'sale_price' => $request->input('sale_price'),
    'category_id' => $request->input('category_id'),
]));
like image 165
Alexey Mezenin Avatar answered Jan 29 '26 04:01

Alexey Mezenin


As i mentioned 1st my form Type PUT and UPDATE method in controller, Create or Save as is not the solution.

Right Answer and solution is to replace save with UPDATE

$updateProduct = $store->product()->where('id', $Product->id)->update([
        'name'=> $request->input('name'),
        'description' => $request->input('description'),
        'normal_price' => $request->input('normal_price'),
        'sale_price' => $request->input('sale_price'),
        'category_id' => $request->input('category_id'),

    ]);

Reminder : For Update method and PUT/PATCH or EDIT use

     DB::table('users')
        ->where('id', 1)
        ->update(['votes' => 1]);

REF : Laravel Docs

like image 36
Hassam Ali Avatar answered Jan 29 '26 05:01

Hassam Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!