php - Filter laravel collection in sub collection
Get the solution ↓↓↓My collection is like this.
Collection {
0 => Name_Model {
"id" => 44
"name" => "The name of "
"list_angg" => Collection {
0 => Name_Model_sub {
"code" => "02"
"nameofcode" => "The name of 02"
}
1 => Name_Model_sub {
"code" => "01"
"nameofcode" => "The name of 01"
}
}
}
1 => Name_Model {
"id" => 45
"name" => "The name of thus"
"list_angg" => Collection {
0 => Name_Model_sub {
"code" => "03"
"nameofcode" => "The name of 3"
}
}
}
}
I want to filter that model by value oflist_angg->code
. So I try like this. Filter and foreach thatlist_angg->code
$jurnals = $filterCollection->filter(function($value, $key) use ($kode_fakultas){
foreach ($value->list_angg as $lists) {
$filtered = $lists->where('code', $kode_fakultas);
return $filtered;
}
return $filtered;
});
dd($jurnals);
I try use methodreject()
andmap()
.
But filter didn't work as well. Is I miss something?
Answer
Solution:
you can do this by first restructuring the collection according to your requirements. For example:
public function formatCollection($collection)
{
$results = [];
foreach ($collection as $item)
{
$results[] = [
'foe' => $item['bar'],
'baz' => $item['foo']
];
}
return collect($results);
}
This will return the required json format and after that you can apply your filters to it. For Example:
$result = formatCollection($collection);
This will return the collection on which you can apply
$result->filter(function(value){
return (value === 'foo');
}
This will return the required information or models you require in your collection.
Answer
Solution:
Hope I understood the question correctly.
To filter all elements whichlist_angg->code
has the given value you can use a combination offilter()
andcontains()
.
$filterCollection->filter(function ($value) use ($code) {
return $value->list_angg->contains('code', $code);
});
filter()
returns all values in a collection which return a truthy value.contains()
returnstrue
orfalse
if a collection contains a value matching the condition provided, which can be a closure, a value or a key and value.
Keep in mindcontains()
uses "loose" comparison, so if you need a strict match you can usecontainsStrict
.
Your code is not filtering correctly because in the filter closure you are always returning the model instance, which evaluates totrue
orfalse
based on the first element and therefore it is considered as a pass or fail based on that.
References:
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: invalid argument supplied for foreach() laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.