-
Notifications
You must be signed in to change notification settings - Fork 66
Creating Custom Filter
Selahattin Ünlü edited this page Nov 11, 2016
·
5 revisions
Remember, this package firstly checks whether it is or not custom filter. (except constant parameters). If there is a custom filter for query parameter, applies it. Otherwise, searches this parameter in the table columns and applies.
-
Create a class derived from QueryBuilder
-
Then, add method into this class. Method name must be study case type and begin with "filterBy". (eg: "filterByName" for "?name" query parameter)
<?php
use Unlu\Laravel\Api\QueryBuilder;
class UserQueryBuilder extends QueryBuilder
{
public function filterByName($query, $name)
{
return $query->where('firstname', $name);
}
}
?>
- Finally, use this class instead of the QueryBuilder class in your controller file.
<?php
namespace App\Whatever\Api\Controllers;
use App\Http\Requests;
use App\User;
use Illuminate\Http\Request;
// Add this line
use YourNameSpace\Path\UserQueryBuilder;
class UsersController extends Controller
{
public function index(Request $request)
{
$queryBuilder = new UserQueryBuilder(new User, $request);
return response->json([
'data' => $queryBuilder->paginate()->result(),
.
.
]);
}
}
?>
You can also use this when you needed the advanced query instead of basic where query.
Example for /api/users?city_name=Istanbul
use Unlu\Laravel\Api\QueryBuilder;
class UserQueryBuilder extends QueryBuilder
{
public function filterByCityName($query, $name)
{
return $query->whereHas('city', function($q) use ($name) {
return $q->where('name', $name);
});
}
}
If you want to access operator you must edit your method:
<?php
use Unlu\Laravel\Api\QueryBuilder;
class UserQueryBuilder extends QueryBuilder
{
public function filterByCityId($query, $id, $operator)
{
return $query->whereHas('city', function($q) use ($id, $operator) {
return $q->where('id', $operator, $id);
});
}
}
?>
<?php
use Unlu\Laravel\Api\QueryBuilder;
class UserQueryBuilder extends QueryBuilder
{
public function filterByCityId($query, $value, $operator, $type)
{
return $query->whereHas('city', function($q) use ($id, $operator) {
return $q->where('id', $operator, $id);
});
}
}
?>
- $type parameter's value is "Basic" as default.
- $type parameter's value will be "In" for whereIn query
- $type parameter's value will be "NotIn" for whereNotIn query