Use multiple filters in Laravel

Viewed 549

I'm desperately looking for a way to make multiple filters on my board. Currently I'm using the filter() function to filter some elements of my array. I would need to display the elements of several arrays with the same key but I can't do it.

My controller:

$arrays = $arrays->filter(function ($item) use ($five, $four, $three, $two){
                return data_get($item, 'note') == $five;
            });

I would need to display the arrays containing the note keys with $five $four $three and $two. Would it be possible to do multiple data_get in the same function?

2 Answers

What you are looking for is not necessarily a filter() but a groupBy() function.

https://laravel.com/docs/7.x/collections#method-groupby

If you are trying to group by the value of a property then all you may need to do is this

$arrays->groupBy('note');

If you are trying to group by something more complex then you can use a callback (similar to your filter)

$arrays->groupBy(function ($item) use ($five, $four, $three, $two) {
    // return the value you wish to group by
    switch ($item->note) {
        case $five:
           return 'five';
        ...
    }
});

If you are wanting to filter by an array of $values then you may want to consider doing something like this instead:

$values = collect([$five, $four, $three, $two]);

$arrays->filter(function ($value) use ($values) {
   return $values->has($value);
});

If you are checking the value of a key -> value pair, the use the contains() method https://laravel.com/docs/7.x/collections#method-contains

If you are checking for the key of a key -> value pair, then use the has() method https://laravel.com/docs/7.x/collections#method-has

Related