How to make dynamic query in laravel 5.3?
Asked Answered
G

1

7

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.

Geriatric answered 24/12, 2016 at 21:19 Comment(1)
Can you give some samples of the kinds of data you have in your database, the kinds of filter requests you're expecting, and how you're expecting the data to look when it's working properly?Sharisharia
H
8

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();
}
Haircloth answered 24/12, 2016 at 23:16 Comment(2)
Great. Can you suggest me how to decide tables based on requested parameters. Because in request I only have columns and filters but I want to make it generic for all. So there is play for table names.Geriatric
Should I store table and respective column names in database and match the requested parameters with that column and take that table name.? Will it affect the overall performance?Geriatric

© 2022 - 2024 — McMap. All rights reserved.