首页 > 解决方案 > 使用 Lumen 通过 URL 传递限制和偏移值

问题描述

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

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

网页.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);
}

请你帮助我好吗?

谢谢,

标签: phplaraveleloquentlumen

解决方案


您可以使用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);
}

推荐阅读