Hi I am developing a rest api endpoint for retrieving paginated list of users. In the frontend, there are options to search with all the listed columns, sort by all columns and filter by name, status and created date.
So far I have created a repository and local scopes in user model for search, sort and filter. This is my code so far. I am confused with the filter option. Since a user a call filter with all the three options. How to pass those values in api in most optimised way?
Controller:
public function index(Request $request)
{
$this->userRepository->getAllUsers($request);
}
Repository function:
public function getAllUsers($request)
{
// Search Parameter
isset($request->q)? $q = $request->q: $q = null;
// Sort Parameter
if ( isset($request->sortby) && (isset($request->direction)) ) {
$sort[$request->sortby] = $request-> direction;
}
return User::where('type','=','student')
->ofSearch($q)
->ofSort($sort)
->paginate($per_page)
}
Model:
public function scopeOfSearch($query, $q)
{
if ( $q ) {
$query->orWhere('name', 'LIKE', '%' . $q . '%')
->orWhere('school', 'LIKE', '%' . $q . '%')
->orWhere('email', 'LIKE', '%' . $q . '%')
->orWhere('phone', 'LIKE', '%' . $q . '%')
->orWhere('class', 'LIKE', '%' . $q . '%');
}
return $query;
}
public function scopeOfSort($query, $sort = [])
{
if ( ! empty($sort) ) {
foreach ( $sort as $column => $direction ) {
$query->orderBy($column, $direction);
}
}
else {
$query->orderBy('users.name');
}
return $query;
}
toArray()
method you can override, so yes, they come after querying the database and receiving the filtered models – ira