Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: orderBy a column with collections

I need to OrderBy a column with collection.

I need to orderBy(updated_at, 'desc') all posts which owned by current logged user.

Here is my code :

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

Here is User model :

class User extends Authenticatable
{
    public function posts()
    {
      return $this->hasMany(Post::class);
    }
}

It doesn't return any errors also doesn't sort !

Any helps would be great appreciated.

P.S:

I know I can achieve this with :

$posts = Post::where('user_id', auth()->user()->id)->orderBy('updated_at', 'desc')->get();

But I would like to do the same thing with collections.

like image 211
Hamed Kamrava Avatar asked Mar 17 '17 10:03

Hamed Kamrava


3 Answers

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

like image 78
DevK Avatar answered Oct 17 '22 17:10

DevK


@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');
like image 6
Hamed Kamrava Avatar answered Oct 17 '22 17:10

Hamed Kamrava


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

like image 3
Jesse de gans Avatar answered Oct 17 '22 17:10

Jesse de gans