【问题标题】:Laravel - How to pass request data in anonymous function inside whereLaravel - 如何在其中的匿名函数中传递请求数据
【发布时间】:2016-06-12 18:28:35
【问题描述】:

所以如果用户没有选择任何选项,我想获取所有项目,否则根据请求数据查询项目。但是我不能将$request 传递给我的函数。这是我的代码:

public function showProducts(Request $request) 
{
       $products = Product::all();
       if(count($request->all()) != 0) {
                $products = Product::where(function($query) {
                    $minPrice = $request['min'] ? $request['min'] : null;
                    $maxPrice = $request['max'] ? $request['max'] : null;
                    $colors = $request['color'] ? $request['color'] : null;
                    $sizes = $request['size'] ? $request['size'] : null;

                    if($minPrice != null && $maxPrice != null) {
                        $query->where('price', '>=', $minPrice)->where('price', '<=', $maxPrice);
                    }

                    if($minPrice == null && $maxPrice == null && $colors == null && $sizes == null)  {

                    }
                })->get();
            }
}

显然,我的 showProducts 闭包中有 $request,但是我无法在 where 内的匿名函数中访问它。如何在匿名函数中使用我的 $request 数据?

【问题讨论】:

    标签: php laravel request eloquent


    【解决方案1】:

    需要使用use关键字从父作用域传入参数:

    $products = Product::where(function($query) use ($request) {
        // $request is now available
    

    现在$request 在您的关闭中可用。

    请看这里:http://php.net/manual/en/functions.anonymous.php#example-200

    【讨论】:

    • 工作就像一个魅力。不知道我必须使用 use 来做到这一点。谢谢!
    • 正是我需要的!我在 Laravel 文档中的任何地方都找不到它,但最后感谢你,我得救了。
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多