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')
]);
}
tonmoybyte liked this reply
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
@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?
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.
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
Ok. I think I understand now. Thanks a lot for clearing things out.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community