0

I have the following MySQL query and I would like to change it to the correct format for Laravel's Query builder.

SELECT DISTINCT(colors) FROM `cards` ORDER BY LENGTH(colors) DESC

This is what I currently have:

table('cards')
    ->orderBy(LENGTH(colors), 'desc')
    ->get();
2
  • I would imagine LENGTH(colors) would need to be in quotes, since it is a string and not a PHP function? Commented Dec 28, 2014 at 18:46
  • @halfer: Yeah, I think you're right. Commented Dec 28, 2014 at 18:50

1 Answer 1

2

Note that you have to use raw methods to be able to run SQL functions like LENGTH().
This should work:

DB::table('cards')
    ->select('colors')
    ->distinct()
    ->orderByRaw('LENGTH(colors) DESC')
    ->get();
Sign up to request clarification or add additional context in comments.

3 Comments

Which one is better? orderBy(DB::raw(...)) vs orderByRaw(...)?
The result is the same so it depends which syntax you like more. I prefer orderByRaw because it's results in less nested parentheses ()
Your answer is mostly correct. You have to add ->select('colors') though. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.