Rohan
Rohan

Reputation: 13781

How do I pass a pre defined callback filter in php?

So I am trying to work with laravel collection filters and I have to filter the collections with a certain callback which looks like so:

        $cases->filter(function ($item) {
            return $item->invention_id != '' || $item->invention_id != null;
        });
        $total->filter(function ($item) {
            return $item->invention_id != '' || $item->invention_id != null;
        });
        $participated->filter(function ($item) {
            return $item->invention_id != '' || $item->invention_id != null;
        });

So how do I abstract this function and then pass that in all 3? Maybe my PHP basics are weak here but I am not sure.

        function filterInventionCases($item)
        {
            return $item->invention_id != '' || $item->invention_id != null;
        }

I can do this but then what? How do I pass this in there?

Upvotes: 2

Views: 435

Answers (1)

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1379

You can call your callback in the filter callback function. Via OOP

$cases->filter(function ($item) {
    $this->filterInventionCases($item);
});
$total->filter(function ($item) {
    $this->filterInventionCases($item);
});
$participated->filter(function ($item) {
    $this->filterInventionCases($item);
});

or

$cases->filter(function ($item) {
    call_user_func('filterInventionCases', $item);
});
$total->filter(function ($item) {
    call_user_func('filterInventionCases', $item);
});
$participated->filter(function ($item) {
    call_user_func('filterInventionCases', $item);
});

Laravel filter need callable type of callback. Or you can try use PHP array_filter function which support string name of the function

array_filter($participated->toArray(), "filterInventionCases");

Upvotes: 1

Related Questions