rur2641 rur2641 - 1 month ago 11
PHP Question

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.

Answer

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; 
       }
    });
 }
Comments