Reputation: 83
I'm trying to achieve pagination and it is working absolutely fine until I add sortByDesc()
along with my eloquent query.
web.php (route file)
Route::get('/', function(){
$posts = Post::simplePaginate(5)->sortByDesc("post_id");
//sortByDesc("post_id") this causes the problem
}
When I prepare the view for the pagination with {{ $posts->links() }}
in the specified view, I get the following error-
Method links does not exist
If I remove the sorting condition from the query, it works perfectly.
What can be the reason behind this behaviour?
Upvotes: 1
Views: 788
Reputation: 2972
To extend to what @RossWilson said.
sortBy
is a collection function, not an eloquent function, the correct eloquent function is orderBy
.
Also, see simplePaginate()
as if you were performing a get(), first(), find()
.
What would you place first the get or the order? ... maybe the get if you want to order a collection (with sortBy
), but since simplePaginate
does not return the same collection that a get()
would return, sortby
does not work. And probably messes up the pagination object/collection.
Upvotes: 3
Reputation: 35170
Try putting the sort on the query rather than the pagination:
Post::orderBy('post_id', 'desc')->simplePaginate(5);
Upvotes: 4