Friday, March 17, 2017

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.



via Hamed Kamrava

Advertisement