23

this is a simplified use case, only to illustrate what I want to achieve:

Considering this query in pure SQL:

SELECT url, 1 AS active
FROM  `modules` 
WHERE 1 

How can I add the constant active column using query builder ?

Here is my Query Builder without the extra column:

DB::table('modules')
->get(['url']);

4 Answers 4

38

Simplest would be to use DB::raw

     DB::table('modules')->get(['url', DB::raw('1 as active')]);
Sign up to request clarification or add additional context in comments.

1 Comment

Please, anyway to do it with eloquent without using DB::raw()?
22

We can add subquery or "custom column" in select with first argument of \Illuminate\Database\Query\Builder::selectSub method as raw SQL or Closure, or \Illuminate\Database\Query\Builder. Better solution is closure or Builder. In your case it will be:

$modules = DB::table('modules')->select('url')
    ->selectSub(function ($query) {
        $query->selectRaw('1');
    }, 'active')
    ->get();

Tested on Laravel 5.5. In closure $query is a object of \Illuminate\Database\Query\Builder for subquery. Prepared SQL will be:

select `url`, (select 1) as `active` from `modules`

Extended example... If we use App\Module eloquent for modules and we need get url of modules and count of their submodules with id > 5, we can write next:

$modules = App\Module::select('url')
    ->selectSub(function ($query) {

        /** @var $query \Illuminate\Database\Query\Builder */
        $query->from('submodules')
              ->selectRaw('COUNT(*)')
              ->where('id', '>', 5)
              ->whereRaw('`modules`.`id` = `submodules`.`module_id`');

    }, 'countOfSubModules')
    ->get();

Prepared SQL will be:

select `url`, 
   (select COUNT(*) from `submodules`
       where `id` > ? and `modules`.`id` = `submodules`.`module_id`)
   as `countOfSubModules` 
from `modules`

Or you can write your example with raw sql:

$sql = 'SELECT 1';
$modules = DB::table('modules')->select('url')->selectSub($sql, 'active')->get();

Then prepared SQL will be:

select `id`, (SELECT 1) as `active` from `modules`

For get all columns necessarily to use select('*'):

App\Module::select('*')->selectSub($sql, 'text')->get();

Not:

App\Module::selectSub($sql, 'text')->get();

5 Comments

Consider explaining a little better what you have done.
I apologize if you are talking about the date of the post. I did not see it at once. I think the solution might be useful. Or do I have a mistake?
I'm not saying your answer is not useful.. I'm just saying it can be even more useful if you explain what you have done.
I changed the description with adding details and maybe rewrite it later. Thanks! Sorry for my English. :)
Very nice! I think we both agree it is much better now. Users can now actually learn something from your answer. I will upvote your answer for your effort. Keep it up, good job! :) Peace
1

Alternative solution if you are using eloquent

$people = Modules::select([
            DB::raw("(SELECT 'CUSTOM_FIELD') as custom_field")
        ])
        ->get();

Comments

-1

Laravel Eloquent has very flexible query builder.

You can specify a column to return as:

$users = DB::table('modules')->select('1 as active')->get(['url']);

3 Comments

I think the solution is close to that, but I get this SQL error when trying your solution: SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'field list' (SQL: select 1 as active from modules)
This will ignore ['url'].
This is not working. I get the same error as ZarkDev. Column not found: 1054 Unknown column '1' in 'field list'

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.