I got a simple problem today. I'm working in a Livewire Component, I have a collection of objects, when I click on an object I want to add it to an array (which works) and then want to remove it from the collection - so that object isn't clickable anymore. What I have:
public function addPartToUsage($partId){
$partToAdd = Part::where('id', '=', $partId)->first();
$this->verwendung[] = ['id'=> $partToAdd->id, 'partBezeichnung'=>$partToAdd->id.':'.$partToAdd->zeichnungsnummer.' - '.$partToAdd->artikelbezeichnung];
$this->partsClient = Part::where('artikelbezeichnung', 'LIKE', '%' . $this->inputsearchpart . '%')
->orWhere('zeichnungsnummer', 'LIKE', '%' . $this->inputsearchpart . '%')
->orderBy('artikelnummer')
->get();
foreach ($this->verwendung as $item) {
if($this->partsClient->contains('id', $item['id'])){
$this->partsClient->forget($this->partsClient->where('id', $item['id'])->id);
} } }
but it is not working because I dont know the key of the element which contains the matching id.
$this->verwendung is my array which holds the id in $this->verwendung[0]['id'] and $this->partsClient is my collection which comes from the database.
How can I modify the collection without making it to an array and then check against matching ids and then recollect? Or better how can I retrieve the matching key of the collection, so that I can use forget() ? Thanks to all here!
CodePudding user response:
Instead of checking if the id is contained in the collection, you can just filter it with reject()
directly
foreach ($this->verwendung as $item) {
$this->partsClient->reject(function ($value, $key) use ($item) {
return $value->id == $item['id'];
});
}
Or simply
$verwendungCollection = collect($this->verwendung);
$idsToRemove = $verwendungCollection->pluck('id')->toArray();
$this->partsClient->reject(function ($value, $key) use ($item) {
return in_array($value->id, $idsToRemove);
});