DataTablesController.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Http\Request;
  5. use Yajra\DataTables\Facades\DataTables;
  6. class DataTablesController extends Controller
  7. {
  8. public function dynamicDataTable($datatableName, Request $request)
  9. {
  10. // Fetch the DataTable configuration
  11. $datatableConfig = DB::table('datatables')->where('name', $datatableName)->first();
  12. if (!$datatableConfig) {
  13. return response()->json(['error' => 'DataTable configuration not found'], 404);
  14. }
  15. // Determine the type of response (default to 'data')
  16. $type = $request->get('type', 'data');
  17. // Start building the query
  18. $query = DB::table($datatableConfig->base_table);
  19. // Apply columns
  20. $select_columns = json_decode($datatableConfig->select_columns, true);
  21. foreach ($select_columns as $column) {
  22. $query->selectRaw($column['select_exp']);
  23. }
  24. // Apply joins
  25. $joins = json_decode($datatableConfig->joins, true);
  26. if (!empty($joins)) {
  27. foreach ($joins as $join) {
  28. if (str_contains($join['table'], '(')) { // Detect subquery joins
  29. $query->join(DB::raw($join['table']), $join['on']['first'], $join['on']['operator'], $join['on']['second'], $join['type']);
  30. } else {
  31. $query->join($join['table'], $join['on']['first'], $join['on']['operator'], $join['on']['second'], $join['type']);
  32. }
  33. }
  34. }
  35. // Apply conditions (filters)
  36. $conditions = json_decode($datatableConfig->conditions, true);
  37. if (!empty($conditions)) {
  38. foreach ($conditions as $condition) {
  39. if (isset($condition['raw'])) {
  40. $query->whereRaw($condition['raw']);
  41. } else {
  42. $query->where($condition['column'], $condition['operator'], $condition['value']);
  43. }
  44. }
  45. }
  46. // Apply sorting
  47. $sorting = $request->order[0] ?? json_decode($datatableConfig->default_sorting, true)[0];
  48. $query->orderBy($sorting['name'], $sorting['dir']);
  49. // Pass query to DataTables
  50. return DataTables::of($query)->make(true);
  51. }
  52. }