php - How to delete this items in laravel5 (array)?
I tried to delete the items I received correctly in foreach :
public function prueba(){
$detallcomanda = Comanda::where('idusuari','=',14)->where('estat','=',0)->get();
if(count($detallcomanda)>0){
foreach($detallcomanda as $detall){
echo $detall->id;
}
}
}
I show the id correctly but when I try to delete with this form in foreach the laravel returns.
Whoops, looks like something went wrong.
$detall->delete($detall->id)
Update
When I try this I recieve the content correctly , but when I use Comanda::destroy the laravel5 don't doing anything.
public function prueba(){
$comanda = Comanda::where('idusuari','=',1)->where('estat','=',0)->get();
$toDelete = array();
foreach($comanda as $detall){
$toDelete[] = $detall->id;
}
var_dump($toDelete);
}
This is the array
array(5) { [0]=> int(41) [1]=> int(42) [2]=> int(43) [3]=> int(44) [4]=> int(45) }
and when I use the following code , destroy doesn't work.
Comanda::destroy($toDelte)
Update2
I doing this
$prueba = json_encode($toDelete);
var_dump($prueba);
And I recieve the id correctly , but now I need to use explode to quit this items "[ ]" , to get only the numbers i don't know how it works explode in laravel or is the same?
string(7) "[38,41]"
Comanda::destroy([10, 14]);
Answer
Solution:
You don't want to delete them individually in a loop like that. It means you're running one query per item to be deleted. Instead gather all the IDs in an array and delete them all in one query:
Answer
Solution:
delete()
doesn't need any parameter. You're already calling the function on a model. Try this:BUT as already pointed out, this is highly inefficient. You should only do that if you have model events that should be triggered by a delete. Otherwise the quickest way is this:
Answer
Solution:
If you query a model, you get a collection. Collections have a method to retrieve model keys. You can use this method to get the keys of the returned models and pass that to Eloquent’s
destroy
method to delete them all in one go:It means you don’t have to do any horrible loops to build temporary arrays just to collect model keys—there’s a method that does that for you.