【问题标题】:Call to a member function paginate() on array when use in variable在变量中使用时调用数组上的成员函数 paginate()
【发布时间】:2021-10-11 04:17:14
【问题描述】:

我从 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 \Binance\API('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);
        }
    }

【问题讨论】:

  • 你传递的 paginate(),在 json_decode 这并不意味着,它会返回一个数组,paginate() 是用于 QueryBuilder 和 eloquent 的,并且在集合中什么的
  • 没有办法分页吗?@Jerson
  • 你可以做到的
  • 我不知道为什么人们只是不阅读错误。调用数组上的成员函数分页...所以你调用 ->paginate() 的变量是一个数组。
  • @Jerson 能否提供更多帮助或提供创建分页的链接

标签: php laravel pagination laravel-livewire


【解决方案1】:

您应该为此使用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,
        ]
    );
});

还有import这个箱子

use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

然后在您的render 方法中,您可以使用collect([...])->paginate(10),如下所示

public function render() {
    try {
        $api = new \Binance\API('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);
    }
}

Reference 用于扩展 paginate 方法和 Collection 使用 macros

【讨论】:

    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多