Skip to content

Instantly share code, notes, and snippets.

@warlord0
Created February 27, 2018 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warlord0/be4bf6ce5d479af9e14688b5061cecd2 to your computer and use it in GitHub Desktop.
Save warlord0/be4bf6ce5d479af9e14688b5061cecd2 to your computer and use it in GitHub Desktop.
Laravel Controller snippet for Datatables.net json return values
/*
Provides data for a jquery DataTable call
*/
public function jsonDataTables(Request $request) {
$draw = 0;
$recordsTotal = MODEL::count();
$query = (new MODEL)->newQuery();
if ($request['columns']) {
// Limit the number of returned columns to those in the table
$columns = (array_map(function($column) {
return $column['data'];
}, $request['columns']));
$query->select($columns);
}
if ($request['search']['value']) {
$query
->where('SEARCHFIELD', 'like', '%'.$request['search']['value'].'%')
->orWhere('SEARCHFIELD', 'like', '%'.$request['search']['value'].'%');
}
$recordsFiltered = $query->get()->count();
if ($request['start']) {
$query->skip($request['start']);
}
if ($request['length']) {
$query->take($request['length']);
}
if ($request['draw']) {
$draw = $request['draw'];
}
if ($request['order']) {
foreach($request['order'] as $key => $val) {
$query->orderBy($request['columns'][$val['column']]['data'], $val['dir']);
}
} else {
$query->orderBy('Ref');
}
$data = $query->get();
return ['recordsTotal' => $recordsTotal, 'recordsFiltered' => $recordsFiltered, 'data' => $data];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment