laravel Eloquent ORM delete() method
Before delete
, there are several methods in laravel.
User::find(1)
and User::first()
return an instance.
User::where('id',1)->get
and User::all()
return a collection of instance.
call delete
on an model instance will returns true/false
$user=User::find(1);
$user->delete(); //returns true/false
call delete
on a collection of instance will returns a number which represents the number of the records had been deleted
//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)
//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0) )
Also there are other delete methods, you can call destroy
as a model static method like below
$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted
One more thing ,if you are new to laravel
,you can use php artisan tinker
to see the result, which is more efficient and then dd($result)
, print_r($result);
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();