【问题标题】:Pagination not showing after I use Resource to display data使用资源显示数据后分页不显示
【发布时间】:2019-08-19 03:18:15
【问题描述】:

使用资源显示数据后,我遇到了分页问题。在此之前,我使用此代码显示数据,输出也显示分页。

输出

控制器

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => $All,
], 200);

但是在我使用资源显示数据之后,分页就消失了。

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => DataResource::collection($All),
], 200);

数据资源

public function toArray($request)
{
    //return parent::toArray($request);
    return [
        'name' => $this->name,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'order' => Resources::collection($this->order)
    ];
}

【问题讨论】:

    标签: php laravel laravel-pagination laravel-eloquent-resource


    【解决方案1】:

    您似乎正在使用Eloquent: API Resources,尽管不确定使用的是哪个版本的 Laravel,因为新版本显示的分页非常不同。

    当我显示第一个 sn-p 的 dump() 时,分页器(也称为 LengthAwarePaginator 对象)位于响应的根目录中:

    LengthAwarePaginator {#406 ▼
      #total: 3
      #lastPage: 1
      #items: Collection {#401 ▶}
      #perPage: 10
      #currentPage: 1
      #path: "http://laravelsoplayground"
      #query: []
      #fragment: null
      #pageName: "page"
      +onEachSide: 3
      #options: array:2 [▶]
    }
    

    应用资源后,分页器仍然存在,但已移至resource 属性。

    AnonymousResourceCollection {#331 ▼
      +collects: "App\Http\Resources\DataResource"
      +collection: Collection {#214 ▶}
      +resource: LengthAwarePaginator {#406 ▶}
      +with: []
      +additional: []
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-11
      • 2018-05-22
      • 2017-12-05
      • 1970-01-01
      • 2021-02-17
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多