Created
January 1, 2017 04:21
-
-
Save toocool/15bb22dae8ea6fca34a179615c36c0b8 to your computer and use it in GitHub Desktop.
Laravel custom class to handle data table queries coming from front end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)