我正在尝试在 laravel 10 中创建自定义分页,但收到错误代码
调用数组上的成员函数 links()
这是我的代码:
CulinaryController.php
public function index(Request $request)
{
$client = new Client();
$qs = http_build_query($request->query());
$qs = $qs ? '?'.$qs : '';
$url = initURLPath("culinary" . $qs);
$response = $client->get($url);
// dd($response->getBody()->getContents());
$json = json_decode((string)$response->getBody()->getContents(), true);
if ($request->query('dd')) {
// dd($response->getBody());
dd($json);
}
$view_data = [
'title' => 'Browse Culinary',
'data' => $json,
];
return view('culinary.index', $view_data);
}
Api/V1/CulinaryController.php
public function index(Request $request)
{
$perPage = $request->query('per_page', 8);
$currentPage = $request->query('page', 1);
$pageOffset = ($currentPage - 1) * $perPage;
$result = Culinary::get();
$data = $result->toArray();
$resultWithPagination = new LengthAwarePaginator(
array_slice($data, $pageOffset, $perPage),
count($data),
$perPage,
LengthAwarePaginator::resolveCurrentPage(),
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'query' => $request->query(),
]
);
return $resultWithPagination;
}
这是导致刀片视图中出现错误的代码:
{{ $data->links() }}
如有任何帮助,我们将不胜感激。
该错误准确地告诉您问题是什么:
调用数组上的成员函数 links()
所以让我们看看你在哪里打电话
links
:
{{ $data->links() }}
因此,您尝试对名为
links
的变量调用 $data
方法。那么让我们看看这个变量来自哪里:
$json = json_decode((string)$response->getBody()->getContents(), true);
// [Snipped]
$view_data = [
'title' => 'Browse Culinary',
'data' => $json,
];
return view('culinary.index', $view_data);
哦。您从
$data
设置 $json
的值,这是 json_decode
将某些 HTTP 响应作为关联数组的结果。
所以是的,
$data
是一个数组。您不能在数组上调用类方法,因为数组不是类。
错误消息很少说谎。如果它告诉您一个变量是一个数组,那么它很可能是一个数组,而不是您认为的对象。因此,如果您逐步执行代码而不是假设,您会发现最终会找到根本问题。