Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mpk123's avatar

passing 2 parameters in a scopeFilter query

How do I go about passing two parameters in a filter query?

The below works but I want to use the $filters[$serviceDate ] instead of hardcoding the date in the last line

 'filters' => Request::all('serviceDate',  'mealType'),
 public function scopeFilter($query, array $filters)
{
        $query
            ->when( $filters['mealType'] ?? null, function ($query, $mealType) {
                $query->whereDoesntHave('student_meals', fn ($query) => 
                    $query->where('meal_type_id', $mealType )
                        ->where('void', false)
						->where('date_served', '2022-06-19')  
            });          
}

I've tried

 ->when( $filters['mealType'] ?? null, function ($query, $mealType, $serviceDate) {
                $query->whereDoesntHave('student_meals', fn ($query) => 
                    $query->where('meal_type_id', $mealType )
                        ->where('void', false)
                        ->where('date_served', $serviceDate));

and get the error:

Too few arguments to function App\Models\Student::App\Models{closure}(), 2 passed in /Applications/XAMPP/xamppfiles/htdocs/Sos/vendor/laravel/framework/src/Illuminate/Conditionable/Traits/Conditionable.php on line 30 and exactly 3 expected

I've tried

->when( ($filters['mealType'] && $filters['serviceDate']) ?? null, function ($query, $mealType, $serviceDate) {
                $query->whereDoesntHave('student_meals', fn ($query) => 
                    $query->where('meal_type_id', $mealType )
                        ->where('void', false)
                        ->where('date_served', $serviceDate));

and get the error: Undefined array key "mealType"

I know I'm missing something basic but struggling to figure it out. Any help is much appreciated.

0 likes
1 reply
mpk123's avatar
mpk123
OP
Best Answer
Level 3

Got the answer from stack overflow:

https://stackoverflow.com/questions/72681431/how-to-pass-2-parameters-in-a-scopefilter-query

Yes, you are missing how to inherit variables from the parent scope. That's is basic knowledge about anonymous function in PHP.

You need to use ($mealType), so the correct code should be like:

public function scopeFilter($query, array $filters)
{
    $mealType = $filters['mealType'] ?? null;
    $serviceDate = $filters['serviceDate'] ?? null;
    $query
        ->when($mealType, function($query) use ($mealType,$serviceDate) {
            $query->whereDoesntHave('student_meals', fn($query) => $query->where('meal_type_id', $mealType)
                ->where('void', false)
                ->where('date_served', $serviceDate)
            );
        });
}

Please or to participate in this conversation.