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!

Looking for a job as Laravel developer? Check out great offers at LaraJobs.com

Leave a Reply

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