Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel DB::update only return 0 or 1

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']; 
    }
like image 841
Shahid Chaudhary Avatar asked Jul 24 '16 11:07

Shahid Chaudhary


2 Answers

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.

like image 57
Leon Vismer Avatar answered Sep 21 '22 06:09

Leon Vismer


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']; 
}
like image 20
Kannan K Avatar answered Sep 23 '22 06:09

Kannan K