Raviya Technical
Published in

Raviya Technical

Laravel Eloquent Query | Laravel Order By Relation Column Example

Now, let’s see an example of laravel order by relation column. you can understand the concept of laravel orderby belongsto relationship. step by step explain orderby in relation to laravel. you will learn orderby relation table laravel. Let’s see below the example laravel orderby relationship column.

In this post, I will give some examples of how to use orderBy with relationoship field in the laravel application. you can easily use order by asc and desc with relation table column in laravel.

This example will help you with laravel.

So, Let’s see the below examples that will help you.

Example 1

Laravel Orderby Belongsto Relationship ASC

$posts = Post::with(['author' => function ($q){$q->orderBy('name');}])->get();

Laravel Orderby Belongsto Relationship DESC

$posts = Post::with(['author' => function ($q){$q->orderBy('name', 'DESC');}])->get();

Example 2

Now we will use collection sortBy() and sortByDesc() method for order by relation column in laravel.

So, let’s see the below examples.

Laravel Orderby Relation Column using Collection ASC

$posts = Post::get()->sortBy(function($query){return $query->auther->name;})->all();

Laravel Orderby Relation Column using Collection DESC

$posts = Post::get()->sortByDesc(function($query){return $query->auther->name;})->all();

Example 3

Now we will use inner join and use order by relation column in laravel.

So, let’s see the below examples.

Laravel Orderby Relation Column using Join ASC

$posts = Post::select('*')->join('authors', 'posts.author_id', '=', 'authors.id')->orderBy('authors.name', 'ASC')->paginate(10);

Laravel Orderby Relation Column using Join DESC

$posts = Post::select('*')->join('authors', 'posts.author_id', '=', 'authors.id')->orderBy('authors.name', 'DESC')->paginate(10);

--

--

--

PHP, Laravel And Flutter Development

Recommended from Medium

How to configure social authentication in a Next.js + Next-Auth + Django Rest Framework application

Tips and Tricks: VictoryChart

//platform.twitter.com/widgets.js from Twitter https://twitter.com/iconbuildgroup

How to open URLs in Flutter

Building TicTacToe with React

Introduction to Koa JS and REST API

What you gonna lose if you choose react over angular

JSON Schema Generator Tools: User Guide 2021

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Raviya Technical

Raviya Technical

raviyatechnical.blogspot.com

More from Medium

Laravel Advance | Laravel US State Seeder Example

Laravel — Installation

Installation laravel

Laravel 8 Toastr Notifications Example

Laravel 8 Send Mail using Queue Tutorial