-
Notifications
You must be signed in to change notification settings - Fork 1
Home
Automatic filtering and sorting for Laravel queries with Ajax capabilities.
In most of Laravel applications there is a need to show data to the user with filtering and ordering capabilities. Usually this is a tedious process and no libraries except for pagination and data representation (JsonResource) are provided.
This library offers a way to easly define filtering and ordering capabilities for the user (Ajax), pagination and resource casting in a well readable and reusable class.
Install it via composer
composer require plokko\resource-query
To initialize ResourceQuery you need to specify the base query; this query will be used in all request and filter and ordering functions will be added to it.
NOTE: The user query may only add filters and will not remove any conditions set on the base query so if you need to apply restriction you should apply on the base query as they are not editable by the user; this applies also to sorting so you should avoid applying ordering in the base query if you want to enable user sorting as the user sorting will be added to the base sorting.
There are two ways of using ResourceQuery: by extending the ResourceQuery class or in-place by using the QueryHelper class. The first approach is more usefull if you plan to use the same query in different places, the second method is more flexible if you plan to use it one time only and you want to avoid the definition of a new class just for that.
Create a new class that extends plokko\ResourceQuery\ResourceQuery and implement the function getQuery() that will return the base query
use App\Models\User;
use plokko\ResourceQuery\ResourceQuery;
class ExampleResourceQuery extends ResourceQuery{
protected function getQuery():Builder {
// Return the base query
return User::select(['id','name','email'])->where('id','>',0); // Just a simple query to demonstrate functionality
}
}use plokko\ResourceQuery\QueryBuilder;
//...
$query = User::select(['id','name','email'])->where('id','>',0);
//Add the base query
$resource = new QueryBuilder($query);class MyController extends Controller {
//...
public function example1(Request $request){
$resource = new ExampleResourceQuery();
if($request->ajax()){
return $resource;//Apply the query to Ajax request
}
view('example',compact('resource'));
}
/**
* Using the builder
*/
public function example2(Request $request){
$query = User::select(['id','name','email'])->where('id','>',0);
$resource = new QueryBuilder($query);
if($request->ajax()){
return $resource;
}
view('example',compact('resource'));
}
//...
}