Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dynamic query in laravel 5.3?

What exactly I wanna do is, I want to make dynamic query in laravel 5.3 based on requested parameters , so in request i will get column names then filters for that query and I don't know tables from which I want to process the data. So, my question is how to decide the tables for that query ? or should I store table and respective columns in one database's table and match the requested parameters with that table so that I will get table name and will able to put in that query?

But I thought this will cost my processing ? so that's why I post this question. please help me with best scenario that will fit with my requirment for dynamic query?

Update

the request will be like this

{
  "col": ['fname', 'lname'],
  "offset": 1,
  "limit": 25,
  "order": [ASC, fname, lname],
  "filter": [
    {
      "col": "id",
      "op": "=",
      "val": 8
    }
  ]
}

so this is my request and table name and related columns are in one table.

like image 686
SaMeEr Avatar asked Dec 24 '16 21:12

SaMeEr


1 Answers

Just use query builders.

$query = DB::table($tableName);

// ...some logic...

foreach ($filters as $filter) {
    $query->where($filter['col'], $filter['op'], $filter['val']);
}

// ...more logic...

if (isset($limit)) {
     $query->limit($limit);
}

if (isset($columns)) {
    // get desired columns
    $records = $query->get($columns);
} else {
    $records = $query->get();
}
like image 52
Mateusz Drost Avatar answered Oct 26 '22 14:10

Mateusz Drost