Skip to content

Instantly share code, notes, and snippets.

@Ahed91
Created October 19, 2020 08:48
Show Gist options
  • Save Ahed91/b5cf1a121a22bf4ae7830449d4133133 to your computer and use it in GitHub Desktop.
Save Ahed91/b5cf1a121a22bf4ae7830449d4133133 to your computer and use it in GitHub Desktop.
Madara DataTables (simple alternative to Yajra DataTables)
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
// define route Route::post('datatable', 'Controller@datatable')->name('datatable');
public function datatable(Request $request)
{
$users_query = Users::query();
// process datatable ajax request and use this callback to build the query
// the search term will be availabel in the nex closure
$data = process_datatable_query($users_query , function (
$query,
$search
) {
return $query
->where(function($query) use ($search) {
$query->where('name', 'like', '%' . $search . '%');
});
});
return $data;
}
}
<?php
// define those two helpers
function get_datatable_params($data)
{
$params = [];
foreach ($data as $key => $value) {
switch ($key) {
case "pagination":
$params["pagination"] = [
"page" => $value["page"],
"perpage" => $value["perpage"]
];
break;
case "query":
$params["search"] = isset($value['generalSearch']) ? $value['generalSearch'] : '';
$params['date_range'] = isset($value['date_range']) ? $value['date_range'] : '';
break;
case "sort":
$params["sort"] = [
"column" => $value["field"],
"dir" => $value["sort"]
];
break;
}
}
return $params;
}
function process_datatable_query($query, $search_callback = null, $post_query = null)
{
$meta = [
'page' => 1,
'pages' => 0,
'perpage' => 12,
'total' => 0,
'sort' => '',
'field' => ''
];
$datatable_params = get_datatable_params(request()->all());
if ($datatable_params['search'] && ($search_callback !== null)) {
$value = $datatable_params['search'];
$query = $search_callback($query, $value);
}
$meta['total'] = $query->count();
$meta['pages'] = (int)ceil($meta['total']/$meta['perpage']);
if ($datatable_params['pagination']) {
$value = $datatable_params['pagination'];
$meta['page'] = (int)$value["page"];
$meta['perpage'] = (int)$value["perpage"];
$offset = ($value["page"] - 1) * $value["perpage"];
$query->offset($offset)->limit($value["perpage"]);
}
if (isset($datatable_params['sort']) && $datatable_params['sort']) {
$value = $datatable_params['sort'];
$query->orderBy($value['column'], $value['dir']);
$meta['sort'] = $value['dir'];
$meta['field'] = $value['column'];
}
if ($post_query) {
$data = $query->get()->pipe($post_query)->toArray();
// $data = $query->get()->toArray();
} else {
$data = $query->get()->toArray();
}
return [
'meta' => $meta,
'data' => $data,
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment