Home > other >  How to pass 2 parameters in a scopeFilter query
How to pass 2 parameters in a scopeFilter query

Time:06-20

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.

CodePudding user response:

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)
            );
        });
}
  • Related