Skip to main content
Tutorial Free

Did you know about orderByRaw() in Eloquent?

December 27, 2016
1 min read

Tutorial last revisioned on August 17, 2022 with Laravel 9

Let's imagine a simple situation - you need to write an Eloquent query and order the result by the difference of two columns. Or some other calculation. Time to apply a raw query! Simple orderBy:
User::where('created_at', '>', '2016-01-01')
  ->orderBy('updated_at', 'desc')
  ->get();
Now, what if we need to order by the difference between updated_at and created_at? It looks like this:
User::where('created_at', '>', '2016-01-01')
  ->orderByRaw('(updated_at - created_at) desc')
  ->get();
This orderByRaw() method, will apply order by clause without changing anything in it, so final query will be:
select * from users
  where created_at > '2016-01-01'
  order by (updated_at - created_at) desc
Hope that helps!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min

How to Build Laravel 13 API From Scratch

30 lessons
1 h 23 min

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.