Doga Doga - 9 days ago 6
PHP Question

Laravel 5.3 Pagination - ErrorException in Collection.php line 432

Every time I try to setup my pagination:


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


My controller:

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

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


My view:

{{ $products->links() }}


What goes wrong here?

Answer

You don't need ->get() here. ->paginate() gets your records from the database and returns a collection of those 15 items.

When you're running ->get() here you're attempting to run it on the collection that is returned which expects a $key and is used to get a specific item out of a collection.

You should do this:

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

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

or with Eloquent

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

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

Note: I have put the filters before the paginate() call to ensure that the where clause is part of the database query rather than trying to filter the resulting collection/paginator

Comments