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?
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.