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]
Build a Basic React App
In this article, we will share with you...How to Upload Image in Laravel 8 using Summernote Editor
Summernote editor is a simple Javascript...jQuery val method
In this article, we will learn how you c...How to change the background color of a web page dynamically using JavaScript
Use the JavaScript style property You...Laravel 5.5 - Login With Only Mobile Number Using Laravel Custom Auth
Today, we are share with you how to modi...