michael
michael

Reputation: 203

Laravel 5 multiple select() in query builder

In laravel 5.1, I want to do like

$myTable = MyTable->select('firstField');

if ($somethingTrue) {
    $myTable->select('secondField');
}

$myTable->get();

where I want both firstField & secondField to be selected.
Of course the code above is not working, i.e. only the secondField is selected in the end.

Is there any function provided by query builder class that can do exactly what I want?

Upvotes: 20

Views: 24512

Answers (3)

Abhay Maurya
Abhay Maurya

Reputation: 12277

mwallisch's answer is better than accepted one because, if you have multiple places where you are defining selects then addSelect wont work.

For instance, following code will throw error:

$myTable = MyTable->select('firstField');
    
if ($somethingTrue) {
    $myTable->addSelect('secondField');
}
    
if ($somethingElseTrue) {
    $myTable->addSelect('thirdField');
}
    
$myTable->get();

while it can be done as:

$fields = ['firstField'];
        
if ($somethingTrue) {
    $fields[] = 'secondField';
}
        
if ($somethingElseTrue) {
    $fields[] = 'thirdField';
}
        
$result = DB::table('users')->select($fields)->get();

Upvotes: 2

mwallisch
mwallisch

Reputation: 1810

Accepted answer is probably more elegant, but you could also just use an array of fields for your select clause.

$fields = ['firstField'];

if ($someCondition) {
    $fields[] = 'secondField';
}

$result = DB::table('users')->select($fields)->get();

Upvotes: 2

Jessedc
Jessedc

Reputation: 12460

Yes, you can use addSelect()

From the Query Builder documentation under "Selects":

If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

Additionally, the API documentation (as apposed to the written documentation) can also shed additional light on what functions are available on core classes.

Upvotes: 41

Related Questions