简体   繁体   中英

combining when() and whereBetween() methods in laravel query builder

I have a Model in Larevel that is taking in parameters for reporting total units in the database.

I want to be able to filter the units returned based on the $entity_ids and the $start and $end dates selected by the user.

entity_ids is working fine with a simple whereIn() method call, but the dates are causing some issue.

My code in Order.php Model is below:

public static function getAllOrdersForReporting($entity_ids, $start, $end) {
    $orders = Order::select('all order information entered here')
    ->whereIn('orders.entity_id', $entity_ids)
    ->when($start && $end, function ($query, $start, $end) { //<-- Error Thrown Here
        return $query->whereBetween('order_date', [$start, $end]);
    })
    ->join('entities', 'entities.id', '=', 'ura_orders.entity_id')
    ->join('entity_address_information', 'entity_address_information.entity_id', '=', 'ura_orders.entity_id')->distinct()->get();

    return $orders;
}

In my ReportingController.php I am entering in the following:

public function displayUnits() {
    $entities = request()->entities_ids;
    $start = request()->start_date;
    $end = request()->end_date;
    $orders = Ura_order::getAllOrdersForReporting($entities, $start, $end);

    return view('reporting.pages.units', compact('entities', 'start', 'end', 'orders'));
}

However when I run this, I get the following error:

Too few arguments to function App\\Models\\Order::App\\Models{closure}(), 2 passed in C:\\xampp\\htdocs\\mywebsite\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Concerns\\BuildsQueries.php on line 91 and exactly 3 expected

Not exactly sure what this error means, except that the Model is seeing only 2 errors passed in and it expected 3.

I marked the line where it is throwing the error up above in the code.

Any advice on how to get this to work? I know the 3rd parameter for when() is supposed to be a callback function, but not sure how to make this work.

You have to use variables in your callback function:

->when($start && $end, function ($query) use ($start, $end) {
    return $query->whereBetween('order_date', [$start, $end]);
})

You can try with this code:

->when($start && $end, function ($query, $condition) use($start, $end) { 
        return $query->whereBetween('order_date', [$start, $end]);
    })

As already pointed in the comments the tihrd parameter of a when() should be a function , with the use() statement you can pass the variables in the closure.

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