Laravel eloquent relationships provides easy way to get relationships data with main table. But sometimes you need to get relationships data with specific column orderBy.
In this article, I will show you how you can get eloquent relationships data with specific column orderBy.
For example, your Post model belongs to User model, and you want to get posts data order by updated_at
. You can get it as following:
$users = User::with(['posts' => function ($query) {
$query->orderBy('updated_at', 'asc');
}])->get();
This method can be used if you only want to get orderBy data once. However if you want to get orderBy on every query, then you can define it in relationships.
<?php
public function posts()
{
return $this->hasMany('App\Models\Post')->orderBy('updated_at', 'desc');
}
I hope you liked this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel 5.5 - Login With Only Mobile Number Using Laravel Custom Auth
Today, we are share with you how to modi...Laravel Amazon S3 File Upload Tutorial
AWS provides fast asset loading for web...How to send Web Push Notification using push.js?
In this article, I will share with you h...How to install latest GIMP in Linux
There are many alternatives open-source...Laravel 5.5 - Task Scheduling With Cron Job Example
Today, we are share in this tutorials &q...