n How to use orderByRaw() in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

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, which is not mentioned in official Laravel documentation, 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!

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook