Reputation:
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?
Upvotes: 1
Views: 735
Reputation: 311
When you call the paginate()
method on a Illuminate\Database\Query\Builder
object, 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 which forwards the call to the underlying Collection.
Now, Illuminate\Support\Collection
does have a get()
method, but it takes the key of the element you want to get out of the Collection as an argument, hence the error you get.
Now, I suppose what you actually want to achieve standard pagination with links for page numbers and "forward" and "back" buttons. If so, you should just stick to the 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.
EDIT: Just read about the Method links does not exist
error you get. That is indeed strange. Builder::paginate()
definitely returns an Instance of LengthAwarePaginator
which itself definitely has a links()
method.
Is there perhaps some more code that is relevant to this problem which you havent shown us yet? Maybe in your view?
Upvotes: 0
Reputation: 16283
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
Upvotes: 2