rur2641
rur2641

Reputation: 699

cannot filter eloquent collection with variable

I can't filter a collection with a variable:

    $sections = Section::all();
    $courses = array("MATH282", "MATH201" , "GEOM202");
    foreach ($courses as $course)
    {
        $sections1 = $sections->filter(function($foo)
        {
            if ($foo->course == $course ) {
            return true;
            }
        });
    }

The filter works if the condition is a string. Everything else works.

Upvotes: 0

Views: 141

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17668

You are missing use() function in filter closure function. Your code should be as:

 $sections = Section::all(); $courses = array("MATH282", "MATH201" , "GEOM202");
 foreach ($courses as $course) { 
    $sections1 = $sections->filter(function($foo) use($course)  { 
       if ($foo->course == $course ) { 
            return true; 
       }
    });
 }

Upvotes: 1

Related Questions