Reputation: 1337
I have a tracking systems which runs on Laravel framework. The tracking systems allow uses to input their tracking query from the website using JSON formatted structure which is then passed to the server fro processing. The server will then query all the relevant data from database based on the JSON structure given in the input. The current code struct is a bit redundant like below:
if($a == true)
{
$data = DB::table('table')
->select('item1')
->where('item2', '=', $a)
->get();
if($limit !== null)
{
$data = DB::table('table')
->select('item1')
->where('item2', '=', $a)
->take($limit)
->get();
}
}
/*the code goes on and on*/
Noted that in the above sample code, is there any way i can do to reduce the redundant parts of the code? like say for example in my mind something like that:
public function process()
{
$data = DB::table('table')
->select('item1')
$a == true ? "->where('item2', '=', $a)" : '';
$limit !== null ? "->take($limit)" : '';
->get();
}
So as you can see the shorten code does exactly the same thing as the long version. I understand my idea is not usable in the real scenario but is there any similar approach that works something like what i have in mind?
Thanks in advance
Upvotes: 0
Views: 1579
Reputation: 964
What I usually do with it is
$query = \DB::table('table');
$query->select('item1'); //i prefer $query->select(\DB::raw('table.item1 AS item1'));
if($a)
{
$query->where('item2', '=', $a);
}
if($limit)
{
$query->take($limit);
}
$data = $query->get();
This way along the way you can make adjustment based on the additional filters to the query you want to add.
Upvotes: 0
Reputation: 6319
The builder builds the query, but the data is not fetched until you run the get
method. Try:
if($a == true)
{
$query = DB::table('table')
->select('item1')
->where('item2', '=', $a);
if($limit !== null)
{
$query->limit($limit);
}
$data = $query->get();
}
limit
is the same as take
. It's just an alias.
Upvotes: 1