Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 982
michael Avatar asked Nov 02 '15 07:11

michael


1 Answers

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.

like image 152
Jessedc Avatar answered Oct 14 '22 00:10

Jessedc