Laravel: orderBy a column with collections

@devk is right. What I wrote in the first post is correct.

The problem was in DataTables in the the view.

It needed to add this line to the Datatables options:

"order": [[ 5, 'desc' ]], // 5 is the `updated_at` column (the sixth column in my case)

So this is working fine :

$posts = auth()->user()->posts->sortByDesc('updated_at');

Try adding the following to your User model

public function posts_sortedByDesc(){
      return $this->hasMany(Post::class)->sortByDesc('updated_at');
   }

Then get the posts by calling posts_sortedByDesc instead of posts


So this is how you sort with SQL:

$posts = auth()->user()->posts()->orderBy('updated_at', 'DESC');

And with collections:

$posts = auth()->user()->posts->sortByDesc('updated_at');

I've tested the 2nd one and it works as intended for me.

Documentation: https://laravel.com/docs/6.x/collections#method-sortbydesc
*Its available since Laravel 5.1