20

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?

1
  • Side note: selectRaw is automatically appended Commented Dec 5, 2022 at 23:52

3 Answers 3

42

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.

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

1 Comment

this is exactly what I needed that you so much!
2

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();

Comments

2

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();

Comments

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.