Skip to content

Commit

Permalink
added fields filter
Browse files Browse the repository at this point in the history
  • Loading branch information
andriy97 committed Mar 27, 2022
1 parent b06687f commit 8236690
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions app/Models/Flyers.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,32 @@ static function getFlyers(){
$now=date('Y-m-d');
$limit=isset(request()->query()['limit']) ? (int)request()->query()['limit'] : 100; //default 100
$allowedFilters=array('is_published', 'category');
$allowedFields=array('id', 'title', 'start_date', 'end_date', 'is_published','retailer', 'category');
//check if query contains not allowed filters
$notAllowedFilters=isset(request()->query()['filter']) ? array_diff_key( request()->query()['filter'], array_flip($allowedFilters)) : array();
//check if query contains not allowed fields
$notAllowedFields=isset(request()->query()['fields']['flyers']) ? array_diff_key( array_flip(explode(",", request()->query()['fields']['flyers'])), array_flip($allowedFields)) : array();


//response for not allowed fields
if(sizeOf($notAllowedFields)>0)
return response()->json([
"success"=> false,
"code"=> 400,
"error"=> array(
"message"=>"Bad Request",
"debug"=>"Not allowed fields: ".implode(", ",array_keys($notAllowedFields))
)
], 200);

$flyers = QueryBuilder::for(Flyers::class)
//default params
->where('start_date', '<=', $now)
->where('end_date', '>=', $now)
//filters
->allowedFilters($allowedFilters)
//request specific fields
->allowedFields($allowedFields)
->paginate($limit)
->appends(request()->query());

Expand All @@ -38,7 +55,9 @@ static function getFlyers(){
"message"=>"Bad Request",
"debug"=>"Not allowed filters: ".implode(", ",array_keys($notAllowedFilters))
)
], 200);;
], 200);



//successful response
$is_empty=$flyers->getCollection()->isEmpty();
Expand All @@ -54,7 +73,7 @@ static function getFlyers(){
"code"=> 404,
"error"=> array(
"message"=>"Not Found",
"debug"=>"No data found with these filters"
"debug"=>"No data found"
)
],200);
}
Expand Down

0 comments on commit 8236690

Please sign in to comment.