where('name', $datatableName)->first(); if (!$datatableConfig) { return response()->json(['error' => 'DataTable configuration not found'], 404); } // Determine the type of response (default to 'data') $type = $request->get('type', 'data'); // Start building the query $query = DB::table($datatableConfig->base_table); // Apply columns $select_columns = json_decode($datatableConfig->select_columns, true); foreach ($select_columns as $column) { $query->selectRaw($column['select_exp']); } // Apply joins $joins = json_decode($datatableConfig->joins, true); if (!empty($joins)) { foreach ($joins as $join) { if (str_contains($join['table'], '(')) { // Detect subquery joins $query->join(DB::raw($join['table']), $join['on']['first'], $join['on']['operator'], $join['on']['second'], $join['type']); } else { $query->join($join['table'], $join['on']['first'], $join['on']['operator'], $join['on']['second'], $join['type']); } } } // Apply conditions (filters) $conditions = json_decode($datatableConfig->conditions, true); if (!empty($conditions)) { foreach ($conditions as $condition) { if (isset($condition['raw'])) { $query->whereRaw($condition['raw']); } else { $query->where($condition['column'], $condition['operator'], $condition['value']); } } } // Apply sorting $sorting = $request->order[0] ?? json_decode($datatableConfig->default_sorting, true)[0]; $query->orderBy($sorting['name'], $sorting['dir']); // Pass query to DataTables return DataTables::of($query)->make(true); } }