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']);
Simplest would be to use DB::raw
We can add subquery or "custom column" in select with first argument of
\Illuminate\Database\Query\Builder::selectSub
method asraw SQL
orClosure
, or\Illuminate\Database\Query\Builder
. Better solution is closure orBuilder
. In your case it will be:Tested on
Laravel 5.5
. In closure$query
is a object of\Illuminate\Database\Query\Builder
for subquery. Prepared SQL will be:Extended example... If we use
App\Module
eloquent for modules and we need geturl
of modules andcount
of their submodules withid > 5
, we can write next:Prepared SQL will be:
Or you can write your example with raw sql:
Then prepared SQL will be:
For get all columns necessarily to use
select('*')
:Not:
Laravel Eloquent has very flexible query builder.
You can specify a column to return as: