| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Http\Request;
- use Yajra\DataTables\Facades\DataTables;
- class DataTablesController extends Controller
- {
- public function dynamicDataTable($datatableName, Request $request)
- {
- // Fetch the DataTable configuration
- $datatableConfig = DB::table('datatables')->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);
- }
- }
|