1

I am trying to convert my mysql query logic to Laravel query builder. I I have no Idea how to convert it as laravel query.

my query logic is

SELECT id,name,
case 
    when visibility_status = '1' 
    then 'Visible' 
    when visibility_status = '0' 
    then 'Invisible'
    end as visibility_status FROM `flowers`

generally I write a select query using query builder but cant implement above logic

$result = DB::table('flowers')
        ->select('flowers.id as id', 'flowers.name as name',
'flowers.visibility_status as visibility_status');
1
  • A different approach might be to add a table to decode the value and then join to it. So you'd have a small table that just had two rows and two columns: 0|Invisible, 1|Visible. Then in either plain SQL or in (non-raw-query) Laravel Query Builder you'd just join from flowers to the decode table and read the value from there. Alternatively, just read the 0 and the 1 and decode them directly in the Laravel View where you output them, assuming that's what you're doing with them. Commented May 2, 2015 at 9:46

1 Answer 1

7

Try This

$users = DB::table('flowers')
->select(["id", "name",
      DB::raw("
       case 
          when visibility_status = '1' 
          then 'Visible' 
          when visibility_status = '0' 
          then 'Invisible'
          end as visibility_status
    ")])->get();

Here is the reference for it http://laravel.com/docs/4.2/queries#raw-expressions

Sign up to request clarification or add additional context in comments.

2 Comments

To note: You'd need PHP 5.4 >= to make this work I believe?
@MackieeE PHP >= 5.4 is a requirement for Laravel anyways

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.