Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Passing extra parameter on Collection filtering

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!

like image 828
Joel Hernandez Avatar asked Jul 06 '14 15:07

Joel Hernandez


1 Answers

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;     }    }); 
like image 96
Jarek Tkaczyk Avatar answered Oct 07 '22 07:10

Jarek Tkaczyk