Wednesday, 5 May 2021

Laravel eloquent Insert() or Update() will return 0 if no row is affected, 1 if 1 row is affected , 2 if 2 rows are affected

 Laravel eloquent Insert() or Update() will return 0 if no row is affected, 1 if 1 row  is affected , 2 if 2 rows are affected


https://stackoverflow.com/questions/38551397/laravel-dbupdate-only-return-0-or-1#:~:text=Laravel%20DB%20update%20function%20returns,because%20update%20values%20are%20same.



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.



No comments:

Post a Comment