dimanche 27 septembre 2015

Building a dynamic laravel DB query using Query Builder

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire