Home » Php » php – Laravel change variable within collection filtering

php – Laravel change variable within collection filtering

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there anyway to make $var = 7 in collection filtering like this?

$var = 1;

$collection->filter(function( $q ) use ($var){
    if( true ){
        $var = 7;
        return true;
    }
});

dd( $var );

Currently this doesn’t work and what I get is still 1

I’ve also tried using global but still I get 1

How to&Answers:

Pass the variable by reference, then it will get changed, e.g.

$collection->filter(function( $q ) use (&$var){
                                      //^ See here