Hi I am studying laravel. I use Eloquent ORM delete method but I get a different result.Not true or false but null. I set an resource route and there is a destroy method in UsersController.
public function destroy($id){
$res=User::find($id)->delete();
if ($res){
$data=[
'status'=>'1',
'msg'=>'success'
];
}else{
$data=[
'status'=>'0',
'msg'=>'fail'
];
return response()->json($data);
But I always get a response {"status":"0","msg":"failed"},the record in the database is deleted.
Then I use dd($res) .It shows null in the page.
But from the course I learn it returns a boolean value true or false.
Is there any error in my code?
Can you tell me some other method that I can get a boolean result when I delete data from database?
This question is related to
php
laravel
laravel-eloquent
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
At first,
You should know that destroy()
is correct method for removing an entity directly via object or model and delete()
can only be called in query builder.
In your case, You have not checked if record exists in database or not. Record can only be deleted if exists.
So, You can do it like follows.
$user = User::find($id);
if($user){
$destroy = User::destroy(2);
}
The value or $destroy
above will be 0 or 1 on fail or success respectively. So, you can alter the $data
array like:
if ($destroy){
$data=[
'status'=>'1',
'msg'=>'success'
];
}else{
$data=[
'status'=>'0',
'msg'=>'fail'
];
}
Hope, you understand.
Laravel Eloquent provides destroy()
function in which returns boolean
value. So if a record exists on the database and deleted you'll get true
otherwise false
.
Here's an example using Laravel Tinker shell.
In this case, your code should look like this:
public function destroy($id)
{
$res = User::destroy($id);
if ($res) {
return response()->json([
'status' => '1',
'msg' => 'success'
]);
} else {
return response()->json([
'status' => '0',
'msg' => 'fail'
]);
}
}
More info about Laravel Eloquent Deleting Models
$model=User::where('id',$id)->delete();
check before delete the user otherwise throws error exeption
$user=User::find($request->id);
if($user)
{
// return $user; <------------------------user exist
if($user->delete()){
return 'user deleted';
}
else{
return "something wrong";
}
}
else{
return "user not exist";// <--------------------user not exist
}
Source: Stackoverflow.com