Laravel orderBy on Eloquent Relationships example

  551 views   7 months ago Laravel

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:

Example:

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

app/Models/User.php

<?php

public function posts()
{
    return $this->hasMany('App\Models\Post')->orderBy('updated_at', 'desc');
}

I hope you liked this article.

Author : Harsukh Makwana
Harsukh Makwana

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]