Trying to get the latest task for each user, so if there is 100 users, I want to get only 10 to display per page but it won't work. When adding the paginate method I get the following error:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
If I remove the method it all works fine, I get the results expected, I just want to paginate. This is my code:
$users = User::with('latestTask')->get()->paginate(10);
You can not paginate a collection
$users = User::with('latestTask')->get();
to paginate you should use method paginate() on Eloquent results:
$users = User::with('latestTask')->paginate(10);
and then in view put the link :
{{ $users->links() }}
You need to call the method directly, without using get()
$users = User::with('latestTask')->paginate(10);
and in your blade you can get the page links using
$variable_name->links()
When you use paginate you then don't need to use get(). just follow the the below code as well.
$users = User::with('latestTask')->paginate(10);
User model will automatically handle the request and get number of data given as argument in paginate($number_of_rows)
method.
you can also use orderBy() in as method chaining format like below.
$users = User::with('latestTask')->orderBy($column,'asc')->paginate(10);
Although other answers are right, I wanted to point out the reason behind it...
get()
executes the query and returns a collection which means you are no longer building/modifying the sql query
paginate()
should be called on the elequent query itself before it's executed so it can add to the query the offset and limit...
That's why it should be
$users = User::with('latestTask')->paginate(10);
You can see in the error that Illuminate\Database\Eloquent\Collection
method paginate doesn't exist because paginate is not a part of the collection
Quoting laravel documentation https://laravel.com/docs/5.8/pagination
There are several ways to paginate items. The simplest is by using the paginate method on the &query builder or an Eloquent query