orderbyraw

Did you know about orderByRaw() in Eloquent?

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:

Now, what if we need to order by the difference between updated_at and created_at? It looks like this:

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:

Hope that helps!

Want more tips and articles like this?
Subscribe to our weekly newsletter - comes out every Thursday!
Join 1200+ Laravel professionals who read the issue weekly.

Leave a Reply

Your email address will not be published. Required fields are marked *