1

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

2
  • does your query string looks like this ?array_field[]=val1&array_field[]=val2 ? Commented Sep 11, 2018 at 12:33
  • @CodeZilla no, unfortunately, that is the problem. This is API I can't control the front end, but I can add validation but will be cool if system convert it automatically Commented Sep 12, 2018 at 2:48

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I try ` is_array($request->input($name));` but it didn't helped
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.