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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With