Skip to content

Instantly share code, notes, and snippets.

@Ahed91
Created June 20, 2017 09:52
Show Gist options
  • Save Ahed91/9e07035534c0abef13c283f75d65ffe0 to your computer and use it in GitHub Desktop.
Save Ahed91/9e07035534c0abef13c283f75d65ffe0 to your computer and use it in GitHub Desktop.
Laravel Pagination with datatables server side
<script>
$(document).ready(function () {
$('#myTable').DataTable({
serverSide: true,
ajax: "{{ url('admin/some/anydata') }}",
lengthMenu: [[1, 25, 50, -1], [1, 25, 50, "All"]],
columns: [
{"data": "id"},
{"data": "sh_name"},
{"data": "sh_price"},
{"data": "sh_owner"},
{"data": "sh_photo"},
{"data": "sh_small_dis"},
{"data": "sh_meta"},
{"data": "created_at"},
{"data": "created_at"}
],
"columnDefs": [
{
"targets": 3,
"data": "sh_owner",
"render": function (data, type, full, meta) {
return full.user.Fname + ' ' + full.user.Sname + ' ' + full.user.Lname;
}
},
{
"targets": 4,
"data": "sh_photo",
"render": function (data, type, full, meta) {
return '<img width="50px" src="' + full.photo.file + '" alt="">';
}
},
{
"targets": 7,
"data": "created_at",
"render": function (data, type, full, meta) {
return full.createdAtHuman;
}
},
{
"targets": 8,
"render": function (data, type, full, meta) {
return '<a class="btn btn-info btn-sm" href="{{ url('admin/some/edit') }}/' + full.id + '">تعديل</a>' +
'<a class="btn btn-danger btn-sm" onclick="return confirm(\'asdasd\')" href="{{ url('admin/some/delete') }}/' + full.id + '">حذف</a>' +
'<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal-' + full.id + '">' +
'تعديل صلاحية الدخول' +
'</button>';
}
}
]
})
});
</script>
class SomeController extends Controller
{
public function anydata(Request $request)
{
$valid_columns = [
'id',
'user_id',
'sh_name',
'sh_price',
'photo_id',
'sh_small_dis',
'sh_meta',
'sh_languid',
'sh_latitude',
'sh_large_dis',
'sh_status',
'created_at',
'updated_at',
];
$columns = $request->get('columns');
$draw = intval($request->get('draw'));
$start = intval($request->get('start'));
$length = intval($request->get('length'));
$order_column_id = $request->get('order')[0]['column'];
$order = $columns[$order_column_id]['data'];
$order = in_array($order, $valid_columns) ? $order : 'id';
$dir = $request->get('order')[0]['dir'];
$dir = in_array($dir, ['asc', 'desc']) ? $dir : 'asc';
$search = $request->get('search')['value'];
$count_all = Some::count();
$query = Some::where('sh_name', 'like', "%" . $search . "%")->orWhere('sh_price', 'like',
"%" . $search . "%");
$count_filtered = $query->count();
$some = $query->with('user')->with('photo')->offset($start)
->limit($length)
->orderBy($order, $dir)->get();
$response = [
"draw" => $draw,
"recordsTotal" => $count_all,
"recordsFiltered" => $count_filtered,
"data" => $some->toArray(),
];
return json_encode($response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment