Laravel 5.3 分页 - Collection.php 第 432 行中的 ErrorException

Laravel 5.3 Pagination - ErrorException in Collection.php line 432

每次我尝试设置分页时:

Missing argument 1 for Illuminate\Support\Collection::get()

我的控制器:

public function index()
{
    $products = DB::table('products')
        ->where('product_group_id', '=', 1)
        ->paginate(15)
        ->get();

    return view('product.index', [
        'products' => $products,
    ]);
}

我的看法:

{{ $products->links() }}

这里出了什么问题?

这里不需要->get()->paginate() 从数据库中获取您的记录和 returns 这 15 项的集合。

当你 运行 宁 ->get() 在这里你试图 运行 它在返回的集合上,它期望 $key 并且用于从集合中获取特定项目。

你应该这样做:

$products = DB::table('products')
    ->where('product_group_id', '=', 1)
    ->paginate(15);

return view('product.index', [
    'products' => $products,
]);

或 Eloquent

$product = Product::where('product_group_id', '=', 1)
    ->paginate(15);

return view('product.index', [
    'products' => $products,
]);

注意: 我在 paginate() 调用之前放置了过滤器,以确保 where 子句是数据库查询的一部分,而不是试图过滤结果 collection/paginator

当您在 Illuminate\Database\Query\Builder 对象上调用 paginate() 方法时,You will get an instance of \Illuminate\Pagination\LengthAwarePaginator. That itself does not have a get()-Method, but the Illuminate\Pagination\AbstractPaginator it extends has a magic __call() function 会将调用转发到基础集合。

现在,Illuminate\Support\Collection have a get() method,但是它将要从集合中取出的元素的键作为参数,因此你得到的错误。

现在,我想您实际上想要通过页码链接以及 "forward" 和 "back" 按钮实现标准分页。如果是这样,您应该坚持 documentation: Get the data just the way you did, just leave out the get(), then display it in a view the way its shown here.

编辑:刚刚阅读了您遇到的 Method links does not exist 错误。这确实很奇怪。 Builder::paginate() 肯定是 returns LengthAwarePaginator 的一个实例,它本身肯定有一个 links() 方法。

是否有更多与您尚未向我们展示的问题相关的代码?也许在你看来?