glasstream2000's avatar

Order by created_at

New here, trying to sort the listings by created_at in desc value.

This code pulls my listings with the newest on the bottom.

$user_id = auth()->user()->id;
        
        $user = User::find($user_id);
        
        return view('dashboard')->with('listings', $user->listings);

This isn't working and I have tried sortBy and nothing seems to work, I'm sure i'm doing/missing something easy here. thanks for any help as i'm learning!

$user_id = auth()->user()->id;
        
        $user = User::find($user_id);
        
        return view('dashboard')->with('listings', $user->listings)->orderBy('created_at', 'desc');
0 likes
5 replies
Cronix's avatar

Do it in the query, it's faster anyway. Laravel has a nice fluent helper for that called latest(), which adds order by created_at desc.

$user = User::latest()->find($user_id);
return view('dashboard')->with('listings', $user->listings);

If you want to order by a column other than created_at, like maybe updated_at, just pass that column to latest(), like latest('updated_at')

https://laravel.com/docs/5.7/queries#ordering-grouping-limit-and-offset

4 likes
Cronix's avatar
Cronix
Best Answer
Level 67

Oh, I think I misunderstood. Let me ask: Is there any time you don't want the listings returned in descending order? Probably not. I'd add ->latest() to the relationship definition.

public function listings() {
     return $this->hasMany(Listing::class)->latest();
}
1 like
cmdobueno's avatar

Additionally you could do something like this (it comes with its own list of bad crap)

$listings = $user->listings()->orderBy('created_at')->get();
3 likes
Cronix's avatar

Not your question, but you're also loading them for the current user. You don't need to perform an additional query and re-retrieve the user since it's already loaded, and you actually don't need to pass anything in the view for that case.

auth()->user()->load('listings');
        
return view('dashboard');
@foreach (auth()->user()->listings as $listing)

if you wish to send it separately

auth()->user()->load('listings');

return view('dashboard')->with('listings', auth()->user()->listings);

and iterate $listings like you were.

1 like
glasstream2000's avatar

Thank you! So many different ways of doing the same thing, it is sometimes confusing lol

Please or to participate in this conversation.