Support the ongoing development of Laravel.io →
Laravel Eloquent
Last updated 2 years ago.
0

The ->save() method to a model will return true even if no changes to the model were made. The ->update() method on a query builder will return an int, you can return that directly.

Both methods return true/1 to me when testing it. Honestly I don't see where's the problem in this code, although I suggest you to go with the uncommented option.

function ServiceUpdate(Request $req) {
   $serviceModel = ServicesModel::findOrFail($req->input('id'));
   
   return (int) $serviceModel->update([
      'service_name' => $req->input('name'),
      'service_des' => $req->input('des'),
      'service_img' => $req->input('img')
   ]);
}
Last updated 2 years ago.

tonmoybyte liked this reply

1
Solution

There is no issue in the code it's just that the update method returns the number of affected rows and not the boolean true or false value.

Here is the link to the official documentation Mass Updates. Please read the last paragraph where the return value of the update method is clearly defined.

If you want to use the commented code then you must change the condition to

  $result= ServicesModel::where('id',$id)->update(['service_name'=>$name,'service_des'=>$des,'service_img'=>$img]);

        if($result){      
           return 1;
         }
        else{
          return 0;
         }

And one more thing you don't need to use the = in where explicitly.

tonmoybyte liked this reply

1
Solution selected by @tonmoybyte

@faisal So, when I don't change anything and click the update button, the update operation returns 0 because no row is changing. That's why I am getting fail message. Is the solution to this using the save() method or can something be done to the update operation?

0

Update method returns the number of affected rows and you are comparing the number with the boolean that's why you are always going in the else part.

0

@faisal But it works when I change something and click the update button.

0

As I said earlier update returns the number of affected rows and the save method just returns the boolean true or false.

And in the If statement, anything greater than 0 is evaluated as true.

tonmoybyte liked this reply

1

Ok. I think I understand now. Thanks a lot for clearing things out.

0

Always happy to help :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.