Skip to content

Instantly share code, notes, and snippets.

@toocool
Created January 1, 2017 04:21
Show Gist options
  • Save toocool/15bb22dae8ea6fca34a179615c36c0b8 to your computer and use it in GitHub Desktop.
Save toocool/15bb22dae8ea6fca34a179615c36c0b8 to your computer and use it in GitHub Desktop.
Laravel custom class to handle data table queries coming from front end
<?php
namespace App\Classes;
use Illuminate\Pagination\LengthAwarePaginator;
class Datatables{
public static function of($query, $queryset){
//accept only the parameters inside this array
$params = $queryset->only(['sortBy', 'sortDirection','pageIndex','pageSize','searchBy','filterBy','filterWhere','filterValue']);
//check if filtering is enabled
if($queryset->has('filterBy') && $queryset->has('filterWhere'))
{
$where = $queryset->input('filterWhere');
$query->whereHas($queryset->input('filterBy'),function($subquery) use ($where){
$subquery->where('name', $where);
});
}
//check if sorting is enabled
if($queryset->has('sortBy') && $queryset->has('sortDirection'))
{
$query->orderBy($queryset->input('sortBy'), $queryset->input('sortDirection'));
}
//check if searching is enabled
if($queryset->has('searchBy'))
{
$query->where('name', 'LIKE', '%'.$queryset->input('searchBy').'%');
}
$currentPage = $queryset->input('pageIndex');
LengthAwarePaginator::currentPageResolver(function() use ($currentPage) {
return $currentPage;
});
$query->paginate($queryset->input('pageSize'));
return $query->orderBy('created_at','desc')->get();
}
}
@toocool
Copy link
Author

toocool commented Jan 1, 2017

Create and Insert the custom class above inside app>Classes>Datatables.php

and in your controller "require" it. like this:
use App\Classes\Datatables;

$products = $currentShop
->products()
->with(['categories' => function($query){
$query->select('name');
}])
->with(['vendor' => function($query){
$query->select('id','name');
}]);

return Datatables::of($products, $request)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment