Laravel eloquent builder has rich features to modify the query. In some cases we wanted to add multiple select in laravel and modify the select statement on basis of few conditions and wanted to add some select statement on condition. so in this article we will learn to add multiple select in laravel eloquent by preserving the last select statement.
By default laravel selects all columns by executing the eloquent query using method first
, get
, paginate
etc and we can also tell the eloquent query builder to which column to select using select
method.
In this tutorial i will use addSelect
to add the multiple select statement in query builder.
Let’s understand it with examples
Example 1
In this example i will create a table article in database and will create a model or QueryBuilder then will add multiple select using addSelect
method.
$query=\DB::table("articles")->select("*")->where("title","test");
dd($query->toSql());
Output of above script will be
"select * from `articles` where `title` = ?"
Let’s add more select statement
$query=\DB::table("articles")->select("*")->select("1 as number")->where("title","test");
dd($query->toSql());
//or
$query=\DB::table("articles")->select("*")->where("title","test");
if($type=='PUBLIC'){
$query = $query->select("1 as number");
}
dd($query->toSql());
Output will be
select `1` as `num` from `articles` where `title` = ?
As you can see now it has removed the *
so in this case we need to add addSelect
here
$query=\DB::table("articles")->select("*")->addSelect("1 as number")->where("title","test");
dd($query->toSql());
//or
$query=\DB::table("articles")->select("*")->where("title","test");
if($type=='PUBLIC'){
$query = $query->addSelect("1 as number");
}
dd($query->toSql());
addSelect
\DB::table(“articles”)->select(“*”)->addSelect(“1 as number”)->where(“title”,”test”)
How to add select in with relation in Eloquent ?
Sometimes we wanted to add select in our relational statement using with to get the specific columns in relational query so we can add that in below way
$query=Article::with(["user"=>function($q){
$q->select("name");
}])->where("title","test")->get();
Here, Article is model name and user is relation with article.
How to add select in subquery in Eloquent ?
In the same way we can add select statement in subquery as we did in relational query.
$query=Article::whereIn("type",function($q){
$q->select("name")->from('users')
->where('type','ADMIN');
})->where("title","test")->get();