【问题标题】:Pass limit and offset values through URL using Lumen使用 Lumen 通过 URL 传递限制和偏移值
【发布时间】:2018-10-05 04:20:00
【问题描述】:

我是 Resfully 服务和 Lumen(Laravel 微框架)的新手。

我想将 /books?limit=10&offset=5 参数传递给控制器​​并将其设置在 json 响应中,但我不知道如何。

web.php

$router->get('/books/', ['uses' => 'BooksController@index']);

BooksController.php

 public function index()
{

  $books = PartnersBooks::where('is_direct', '=', 1)
      ->with('direct')
      ->whereHas('direct', function ($query) {
          $query->enable()
          ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
      })
      ->offset(5) // This should have an default value until the user pass a value through url
      ->limit(30) // This should have an default value until the user pass a value through url
      ->orderBy('id', 'asc')
      ->get(['id', 'category', 'description']);

      $status = !is_null($books) ? 200 : 204;
      return response()->json($books, $status);
}

你能帮帮我吗?

谢谢,

【问题讨论】:

    标签: php laravel eloquent lumen


    【解决方案1】:

    您可以使用Request 对象来做到这一点:

    use Illuminate\Http\Request;
    
    
    public function index(Request $request)
    {
        $limit = $request->input('limit');
        $offset = $request->input('offset');
    
        $books = PartnersBooks::where('is_direct', '=', 1)
          ->with('direct')
          ->whereHas('direct', function ($query) {
              $query->enable()
                ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
          })
          ->offset($offset) // This should have an default value until the user pass a value through url
          ->limit($limit) // This should have an default value until the user pass a value through url
          ->orderBy('id', 'asc')
          ->get(['id', 'category', 'description']);
    
         $status = !is_null($books) ? 200 : 204;
         return response()->json($books, $status);
    }
    

    【讨论】:

    • $request->input() 也接受第二个参数作为默认值。所以你可以设置一个这样的默认值:$offset = $request->input('offset', 5)。限制类似。
    • 完成!谢谢!
    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多