在变量中使用时调用数组上的成员函数paginate()



我从web服务获得信息,但当我尝试进行分页时给出此错误我看到其他问题,但他们都从数据库中获取信息,并没有帮助我的问题。

Call to a member function paginate() on array (View: /media/mojtaba/Work/Project/bit/resources/views/backend/crypto/cryptolist.blade.php)

和我的代码

public function render()
{
try {
$api = new BinanceAPI('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins->paginate(10));
}catch(Exception $e)
{
return view('wrong')->with('e' , $e);
}
}

您应该使用Collection,但收集没有paginate方法,但我们可以使用macrosextend

打开AppServiceProvider.php并粘贴到boot方法

Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});

alsoimportthis incase

use IlluminateSupportCollection;
use IlluminatePaginationLengthAwarePaginator;

那么在你的render方法中你可以使用collect([...])->paginate(10),就像下面的

public function render() {
try {
$api = new BinanceAPI('api','secret');
$coins = $api->coins();
return view('livewire.backend.crypto.cryptolist')->with('coins',collect($coins)->paginate(10));
} catch(Exception $e) {
return view('wrong')->with('e' , $e);
}
}

macros扩展Collectionpaginate方法的参考。

最新更新