Reputation: 1494
Is there a way to filter a collection returned by database query on Laravel?
Returned collection is this
1 => Person {#310 ▼
#table: "person"
#attributes: array:15 [▼
"name" => "Jon Doe"
"timeavailable" => "1,2,3,4,5,6,7,8"
2 => Person {#310 ▼
#table: "person"
#attributes: array:15 [▼
"name" => "Jon Moe"
"timeavailable" => "1,2,5,7,8"
Here, I want to filter the timeavailable
attribute. I only want to show results for 1,2,3
. Is there a way to filter this collection so that I only get something like this
1 => Person {#310 ▼
#table: "person"
#attributes: array:15 [▼
"name" => "Jon Doe"
"timeavailable" => "1,2,3"
2 => Person {#310 ▼
#table: "person"
#attributes: array:15 [▼
"name" => "Jon Moe"
"timeavailable" => "1,2"
So, the filtered collection will have only 1,2,3
inclusions.
Upvotes: 1
Views: 785
Reputation: 7083
I think this is not the best solution, but it can be a way to solve for this problem. Check if this helps...
Try to use the map
of Collection
. In the inner function, you can explode, intersect and explode timeavailable
.
$limiter = [1,2,3];
$filtered = $array->map(function($person, $k) use ($limiter) {
$ex = explode(',', $person->timeavailable);
$intersect = array_intersect($limiter, $ex);
$person->timeavailable = implode(",",$intersect);
return $person;
});
This will work fine for small results, but if you are planning to run this with lots of results, it will be slow.
Upvotes: 1