38

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!

Joel Hernandez
  • 1,817
  • 4
  • 18
  • 27
  • 1
    Or you can just do `return !in_array($game->id,$games_already_added)` – Yang Jul 06 '14 at 16:01
  • @djay indeed djay , but my issue here was not being able to access to the games_already_added array , however , thanks for the shorter line! – Joel Hernandez Jul 06 '14 at 16:05

2 Answers2

108

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;
    }   
});
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
3

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.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75