简体   繁体   中英

How to pass 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM