Reputation: 1323
I'm building an API with custom query filter, in my filter, there are rules that value cannot be empty and some fields has to be an array.
I have managed to filter out empty fields if they are submitted but I can't convert request input to the array, is there a way to do it?
Here is my code:
public function removeEmptyFieldsFromRequest($request)
{
$emptyFields = [];
foreach ($request->all() as $name => $value)
{
if (is_null($value)){
$emptyFields[] = $name;
}
$fields = ['transmissions', 'grades', 'colors', 'equipment', 'lots', 'chassis', 'auctions', 'models'];
if (in_array($name, $fields)){
// here need to convert request value from a string into the array
}
}
$request = $request->except($emptyFields);
return $request;
}
I want to make this filter usable in different cases, I know that I can change the input name to the array on the front end
Upvotes: 1
Views: 2495
Reputation: 785
if you query string is like this : /?a=1&b=2&a=3&c=1&a=2
.
You can create a function that parses the query string something like this:
$uri = explode('?', Request::capture()->getRequestUri());
$queryStringArr = explode('&',$uri[1]);
$params = [];
foreach ($queryStringArr as $item) {
$i = explode('=',$item);
if (!empty($params[$i[0]])){
$params[$i[0]]=array_merge((is_array($params[$i[0]]))?$params[$i[0]]:[$params[$i[0]]],[$i[1]]);
}else{
$params[$i[0]]=$i[1];
}
}
print_r($params);die;
Which gives.
Array
(
[a] => Array
(
[0] => 1
[1] => 3
[2] => 2
)
[b] => 2
[c] => 1
)
I haven't tested it much so give it a thought yourself.
Upvotes: 1
Reputation: 31
In Laravel if your parameters is like field[0],field[1],...
you can get it with $request->field
and it is array so you can check
is_array($request->field)
and in your case you can check it with below code
is_array($value)
Upvotes: 1