dongzhoulong1797 2016-04-03 17:28
浏览 2624

Laravel查询字符串少于/大于等

In laravel, I can write this in a resource controller to respond to get requests (let's say the resource is products):

public function index(Request $request)
{
    // Handles requests such as ".../api/products?user_id=5&price=500"
    $products = Product::where($request->toArray())->get();
    return response($products);
}

This works fine for requests with "=", such as in the example. But what if we don't want to search for price=500, but perhaps price <= 500 or price > 500. What would be the best Laravel (and RESTful) approach for this?

Note: Laravel 5.2

  • 写回答

1条回答 默认 最新

  • dongshang4984 2016-04-03 17:38
    关注

    You can do like this.

    public function index(Request $request)
    {
        // Handles requests such as ".../api/products?user_id=5&price=500"
        $products = Product::where('user_id', $request->user_id)->where('price', '<=', intval($request->price))->get();
        return response()->json($products);
    }
    

    Or:

    public function index(Request $request)
    {
        // Handles requests such as ".../api/products?user_id=5&price=500"
        $products = Product::whereRaw("user_id=? and price<=?", [$request->user_id, $request->price])->get();
        return response()->json($products);
    }
    

    Edit after @Joel Hinz comment:

    If you want also to pass the operator of the query you can add a new parameter to the url, for example

    /api/products?user_id=5&price=500&op=1
    

    Then switch the number in the controller.

    public function index(Request $request)
    {
        // Handles requests such as ".../api/products?user_id=5&price=500&op=1"
        switch(intval($request->op)){
            case 1:
            $op = "<=";
            break;
    
            case 2:
            $op = ">";
            break;
    
            //and so on
    
            default:
            return response()->json("Wrong parameters");
            break;
        }
    
        $products = Product::whereRaw("user_id = ? and price $op ?", [$request->user_id, $request->price])->get();
        return response()->json($products);
    }
    
    评论

报告相同问题?