I would like to find a way to check if my query result doesn't return a value. Example: If in my tableExample on database there isn' t the id that I'm passing , the method should return an exception or a simple echo that indicate me the not presence in the table
My code below:
try{
DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
return $result= array("result" => "true" );
}catch(QueryException $e){
return $result= array("result" => "false" );
echo " - ".$e;
}
}
update
method return integer value ( affected rows
) if success, try like this
try{
$update = DB::table('tableExample')
->where('id', "2")
->update(['update' => "1"]);
if($update){
$result = array("result" => true );
}else{
$result = array("result" => false,"message"=>"Not Found" );
}
}catch(QueryException $e){
$result = array("result" => false,"message"=>$e->getMessage() );
}
return $result;
Use findOrFail()
helper method. That way you do not need to wrap the action in a try catch
since if findOrFail does not find the row then it will throw an exception.
$resultData = DB::table('tableExample')->findOrFail(2);
$update = $resultData->update(['update' => "1"]);
if(!$update){
return response(['results'=>false]);
}
return response(['results'=> true]);
}
update()
method returns a boolean true for success on update and versa.
You can do this by using the whereExists
clause:
https://laravel.com/docs/5.5/queries#where-exists-clauses
https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html#method_exists
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.