Laravel DB update
function returns 0 if the query failed or if the row was not affected because update values are same.
How can I check if the query failed because of an error or because the row was not affected? In the below code, if values are the same, it will return and won't run the next set of code in the controller.
$query = DB::table('users')
->where('id', '=' , $requestdata['user_id'] )
->update([
'first_name' => $requestdata['user_fname'],
'last_name' => $requestdata['user_lname'],
]);
if ( !$query ) {
return ['error' => 'error update user'];
}
An update query returns the number of rows that where affected by the update query.
$returnValue = DB::table('users')
->where('id', '=', $data['user_id'] )
->update([
'first_name' => $data['user_fname'],
'last_name' => $data['user_lname'],
]);
So the above will return the number of records that where updated. 0
means that no records have been updated.
However, for you it might also not signify an error even if a 0
was returned as it just means that no records where updated. So if you try to update the name and lastname of a user with the details it actually already contains the query will return 0
.
Useful side note, play with php artisan tinker
, ie.
>>> $retval = DB::table('users')->where('id', 1)->update(['first_name' => 'Testing']);
=> 1
run the same query again and you will notice it returns 0
affected rows as the name is already Testing
>>> $retval = DB::table('users')->where('id', 1)->update(['first_name' => 'Testing']);
=> 0
Updated addition:
So for you it might be better to first check if the user exists with either a User::findOrFail($id)
or just check the return of User::find($id)
and then if the user exists you do your conditional update on the returned $user
. It is more explicit as update returns the same 0
for a non-existent user and a if the user details already where what you are trying to set it to.
You can use try catch:
try {
$query = DB::table('users')
->where('id', '=' , $requestdata['user_id'] )
->update([
'first_name' => $requestdata['user_fname'],
'last_name' => $requestdata['user_lname'],
]);
} catch(\Illuminate\Database\QueryException $ex){
return ['error' => 'error update user'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With