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.
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
@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
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