Muhammad Abdullah Ali
Muhammad Abdullah Ali

Reputation: 83

Data not getting updated laravel 5.2

I'm trying to update a row in a particular table, laravel does not shows any error but value is not updating in database.

this is my update method code:

function update(Request $request){

  $product=product::find($request['Id']);
  $product->productName=$request['name'];
  $product->description=$request['desc'];
  $product->discount=$request['discount'];
  $product->inventory=$request['inventory'];
  $product->save();

  return response()->json(['message'=>$product->productName],200);
}

I'm successfully getting all the data and I've checked that my changing the value of response json

the variable $product->productName also shows updated value as it is present after save() method but nothing changes in database.

The problem is with this piece of code as I have checked my model i.e product and its working fine as $product has value.

Upvotes: 0

Views: 517

Answers (2)

omitobi
omitobi

Reputation: 7334

Are you not trying to update this record?

Why are you using save() method, why not use update() since you are trying to set the given product with new set of values?:

 $product->update();

So you can finally have (suggesting a check on if a product exists and if the update was successful - you can disregard it if you like):

function update(Request $request)
{
      if(!$product=product::find($request['Id']))
      {
          return response()->json('Product does not exist', 404);
      }
      $product->productName=$request['name'];
      $product->description=$request['desc'];
      $product->discount=$request['discount'];
      $product->inventory=$request['inventory'];
      if($product->update())
      {
          return response()->json(['message'=>$product->productName],200);
      }

      return response()->json('Something went wrong', 500);  
}

Hope it helps :)

Upvotes: 0

thefallen
thefallen

Reputation: 9749

By default Laravel is protecting all models from mass-assignment vulnerability. So you have to specify either a $fillable (which fields can be modified) or $guarded (which fields can not be modified) property.

In your case add this to the model:

protected $fillable = [
    'productName',
    'description',
    'discount',
    'inventory',
];

Upvotes: 2

Related Questions