php – Laravel : Passing extra parameter on Collection filtering-ThrowExceptions

Exception or error:

the idea it’s quite simple, however I have not yet been able to materialize it.

Here’s the code

(I’ve changed the name of the variables to describe their use)

    $games = Game::all();
    $games_already_added = $member->games()->lists('id');

    $games = $games->filter(function($game){
        global $games_already_added;
        if(!in_array($game->id,$games_already_added)){
            return true;
        }   
    });

When the code is executed I receive the error

in_array() expects parameter 2 to be array, null given

I have verified that the variable $games_already_added is defined on the outer scope and contains items.

Is there any way I could pass the $games_already_added variable as a parameter on the collection’s filter function ?

Any kind of suggestion’s or guidance are highly appreciated !

Thank you!

How to solve:

It’s not global, but use that works with a Closure:

$games = $games->filter(function($game) use ($games_already_added) {
    if(!in_array($game->id,$games_already_added)){
        return true;
    }   
});

Answer´╝Ü

This isn’t strictly what you’re trying to do – but it looks like it’s what you want to achieve.

$games_already_added = $member->games()->lists('id');
$games = Game::whereNotIn('id', $games_already_added)->get();

But if you really want to do the filtering, @deczo’s answer is the way to go.

Leave a Reply

Your email address will not be published. Required fields are marked *