Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Pagination Latest Rows (Reversed)

Can't find an example anywhere on how to return latest rows (per the created_at column) within pagination?

My current code is:

$messages = Message::where('to_id', $user->id)
    ->where('is_read', false)
    ->paginate(10);

I want to sort the results by most recent. How do I do this?

like image 575
TJH Avatar asked Feb 02 '17 20:02

TJH


2 Answers

You can use the latest() method which is a shortcut to orderBy('created_at', 'desc')

$messages = Message::where('to_id', $user->id)
    ->where('is_read', false)
    ->latest()
    ->paginate(10);

In order to use ->latest() you must have a column created_at in your table.

like image 60
Alexey Mezenin Avatar answered Oct 10 '22 10:10

Alexey Mezenin


Try to orderBy id DESC:

$messages = Message::where('to_id', $user->id)
->where('is_read', false)
->orderBy('id', 'DESC')
->paginate(10);

Or by created_at:

$messages = Message::where('to_id', $user->id)
->where('is_read', false)
->orderBy('created_at', 'DESC')
->paginate(10);

Also you can use latest():

$messages = Message::where('to_id', $user->id)
->where('is_read', false)
->latest()
->paginate(10);
like image 35
Buglinjo Avatar answered Oct 10 '22 10:10

Buglinjo