PHP code example of chandra-hemant / server-side-datatable

1. Go to this page and download the library: Download chandra-hemant/server-side-datatable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chandra-hemant / server-side-datatable example snippets


use ChandraHemant\ServerSideDatatable\FlexibleDataTable;

// Simple DataTable response
return FlexibleDataTable::of(new User())
    ->searchable(['name', 'email', 'phone'])
    ->orderable(['name', 'email', 'created_at'])
    ->make();

// Complex query with all Laravel functions
return FlexibleDataTable::of(new Order())
    // Basic Laravel query methods
    ->where('status', 'completed')
    ->whereIn('type', ['online', 'offline'])
    ->whereNotNull('payment_date')
    ->whereBetween('total_amount', [100, 5000])
    ->whereDate('created_at', '>=', '2024-01-01')
    ->whereYear('created_at', 2024)
    ->whereRaw('total_amount > (SELECT AVG(total_amount) FROM orders)')
    
    // Relationships
    ->whereHas('customer', function($query) {
        $query->where('is_verified', true);
    })
    ->with(['customer', 'products', 'payments'])
    ->withCount(['products', 'payments'])
    ->withSum('products', 'price')
    
    // Joins and grouping
    ->join('customers', 'orders.customer_id', '=', 'customers.id')
    ->groupBy('customer_id')
    ->having('total_orders', '>', 5)
    
    // Search configuration
    ->searchable(['order_number', 'total_amount'])
    ->searchableRelation('customer', ['name', 'email'])
    ->searchableRelation('products', ['name', 'sku'])
    
    // Ordering configuration
    ->orderable(['order_number', 'total_amount', 'created_at'])
    ->orderBy('created_at', 'desc')
    
    // Return DataTable response
    ->make();

// 1. DataTable JSON response (for AJAX)
$dataTableResponse = FlexibleDataTable::of(new Product())
    ->where('is_active', 1)
    ->searchable(['name', 'sku'])
    ->make();

// 2. Collection of models (for other uses)
$products = FlexibleDataTable::of(new Product())
    ->where('is_active', 1)
    ->searchable(['name', 'sku'])
    ->get();

// 3. Query builder (for further customization)
$query = FlexibleDataTable::of(new Product())
    ->where('is_active', 1)
    ->searchable(['name', 'sku'])
    ->getQuery();

// Add more conditions to the query
$finalResults = $query->where('category_id', 5)->paginate(15);

// Conditional logic
FlexibleDataTable::of(new Transaction())
    ->when(request('status'), function($query, $status) {
        $query->where('status', $status);
    })
    ->unless(request('uest('filter'))
    ->make();

// Year filtering helper
FlexibleDataTable::of(new Sale())
    ->filterByYear('sale_date', 2024)
    ->make();

use ChandraHemant\ServerSideDatatable\FlexibleDataTable;

class ProductController extends Controller
{
    public function index()
    {
        if (request()->ajax()) {
            return FlexibleDataTable::of(new Product())
                ->select(['id', 'name', 'price', 'category_id'])
                ->where('is_active', true)
                ->whereIn('category_id', [1, 2, 3])
                ->when(request('min_price'), function($query) {
                    $query->where('price', '>=', request('min_price'));
                })
                ->searchable(['name', 'sku', 'description'])
                ->searchableRelation('category', ['name'])
                ->with(['category', 'images'])
                ->withCount(['reviews'])
                ->withAvg('reviews', 'rating')
                ->orderable(['name', 'price', 'created_at'])
                ->orderBy('name')
                ->make();
        }
        
        return view('products.index');
    }
}

use ChandraHemant\ServerSideDatatable\DynamicModelDataTableHelper;

$dynamicConditions = [
    [
        'method' => 'whereColumn',
        'args' => ['column1', '>=', 'column2'],
        'condition' => 'loss'
    ],
    [
        'method' => 'whereRaw',
        'args' => ['YEAR(column3) = ?', session()->get('financialYear')]
    ],
    [
        'method' => 'whereIn',
        'args' => ['column4', session()->get('values')]
    ],
    [
        'method' => 'where',
        'args' => ['column6', 0]
    ],
    [
        'method' => 'whereHas',
        'args' => ['column7', 'LIKE', $request->input('status')],
        'relation' => 'o_status'
    ],
    [
        'method' => 'select',
        'args' => ['column1','column2','column3','column4','column5'],
        'relation' => ['relation1','relation2','relation3','relation4','relation5'],
    ],
    [
        'method' => 'orderBy',
        'args' => ['column1', 'desc']
    ]
];

$searchColumns = ['column1','column2','column3','column4','column5'];

$searchRelationships = [
    'relation1' => ['column1'],
    'relation2' => ['column2'],
    'relation3' => ['column3'],
];

$helper = new DynamicModelDataTableHelper(
    eloquentModel: new YourModel(),
    dynamicConditions: $dynamicConditions,
    searchColumns: $searchColumns,
    searchRelationships: $searchRelationships
);

$result = $helper->getServerSideDataTable();

$dynamicConditions = [
    [
        'method' => 'nestedCondition',
        'parentMethod' => 'where',
        'nestedMethod' => [
            [
                'childMethod' => 'where',
                [
                    'method' => 'where',
                    'args' => ['column1', '=', 5]
                ],
                [
                    'method' => 'whereIn',
                    'args' => ['column2', [1, 4, 7]]
                ],
            ],
            [
                'childMethod' => 'orWhere',
                [
                    'method' => 'where',
                    'args' => ['column1', '!=', 5]
                ],
                [
                    'method' => 'whereIn',
                    'args' => ['column3', [1, 4, 7]]
                ],
            ],
        ],
    ],
    [
        'method' => 'nestedRelationCondition',
        'parentMethod' => 'whereHas',
        'relation' => 'relationship_method',
        'args' => [['column1', $user->id], ['column2', $statusId]],
        'nestedMethod' => [
            [
                'childMethod' => 'whereDoesntHave',
                'relation' => 'relationship_method1',
                'nestedConditions' => [
                    [
                        'method' => 'where',
                        'args' => ['log_request_id', $requestId]
                    ]
                ]
            ]
        ]
    ]
];

use ChandraHemant\ServerSideDatatable\DataTableHelper;

// Specify columns, ordering, and filtering conditions
$column = array(
    'table'=> 'products',
    'order'=> array(
        array('products', 'prod_id'),
        array('products', 'prod_name'),
        array('products', 'prod_type'),
        array('productCategory', 'cat_name')
    ),
    'select'=>array(
        array('products', 'prod_id'),
        array('products', 'prod_name'),
        array('products', 'prod_type'),
        array('productCategory', 'cat_name')
    ),
    'where'=>array(
        array('column' => 'products.mf_id', 'operator' => '=', 'value' => '1')
    ),
    'orderBy'=>array(
        array('column' => 'products.prod_id', 'direction' => 'DESC')
    ),
);

// Specify join conditions and types
$join = array(
    'tables'=> array(
        array('productCategory', 'products'),
    ),
    'fields'=>array(
        array('cat_id', 'cat_id'),   
    ),
    'joinType'=>array(
        'left', 
    ),
);

$list = DataTableHelper::getServerSideDataTable($column, $join);
$count = DataTableHelper::countFilteredServerSideDataTable($column, $join);

// Process data for DataTable response
$data = array();
foreach ($list as $val) {
    $row = array();
    $row[] = '#'.$val->prod_id;			
    $row[] = $val->prod_name;			
    $row[] = $val->prod_type;						
    $row[] = $val->cat_name;	
    $data[] = $row;
}

$output = array(
    "draw" => request()->input('draw'),
    "recordsTotal" => sizeof($list),
    "recordsFiltered" => $count,
    "data" => $data,
);

return response()->json($output);

use ChandraHemant\ServerSideDatatable\ModelDataTableHelper;

$column = [
    'orderBy' => [
        ['column' => 'prod_id', 'direction' => 'DESC'],
        ['column' => 'productCategory.cat_name', 'direction' => 'ASC'],
    ],
    'order' => [
        ['prod_id'],
        ['prod_name'],
        ['prod_type'],
        ['productCategory.cat_name'],
    ],
    'select' => [
        ['prod_id', 'id'],
        ['prod_name', 'name'],
        ['prod_type', 'type'],
        ['productCategory.cat_name', 'category_name'],
    ],
    'with' => [
        ['relation'=>'audit_employee'],
        ['relation'=>'audits', 'nested' => [
            'relation' => 'user_detail', 
            'selectColumn' => ['emp_id', 'emp_name']
        ]],
    ],
    'where' => [
        ['column' => 'productCategory.mf_id', 'operator' => '=', 'value' => 'encrypted_value', 'encrypted' => true],
        ['column' => 'YEAR(created_at) = ?', 'operator' => '=', 'value' => '2024', 'isRaw'=>true],
        ['column' => 'category.type', 'operator' => '!=', 'value' => '["5","6"]', 'isArray'=>true],
        ['column' => 'price', 'operator' => '=', 'value' => 'cost', 'isColumn' => true],
    ],
];

$list = ModelDataTableHelper::getServerSideDataTable(new Product(), $column);