首页 > 解决方案 > Laravel 分页不存在

问题描述

我正在尝试创建分页,问题是,当我尝试创建分页时出现此错误

方法 Illuminate\Database\Eloquent\Collection::pagination 不存在。

我正在使用 laravel 和 livewire。

这是我的代码

    $products = $this->category->products->pagination(10);

这是在我的类别模型中

    public function products()
    {
        return $this->hasMany(Product::class);
    }

更新

这是我的 livewire 的全部代码

    <?php

    namespace App\Http\Livewire\Categories;

    use Illuminate\Pagination\Paginator;
    use Livewire\Component;

    class Show extends Component
    {
        public $category;

        public function render()
        {
            $products = $this->category->products->paginate(10);

            return view('livewire.categories.show', ['category' => $this->category, 'products' => $products]);
        }
    }

和我的 livewire.categories.show 刀片文件

<table class="min-w-full divide-y divide-gray-200">
    <tbody>
        @foreach($products as $product)
            <tr>
                <td>
                    {{ $product->name }}
                </td>
            </tr>
        @endforeach
    </tbody>
</table>

<div>
    {{ $products->links() }}
</div>

标签: phplaravellaravel-8laravel-livewire

解决方案


您忘记使用Livewire 文档WithPagination中所述的特征。

<?php

namespace App\Http\Livewire\Categories;

use Illuminate\Pagination\Paginator;
use Livewire\Component;
use Livewire\WithPagination;

class Show extends Component
{
    use WithPagination;

    public $category;

    public function render()
    {
        $products = $this->category->products()->paginate(10);

        return view('livewire.categories.show', ['category' => $this->category, 'products' => $products]);
    }
}

推荐阅读