Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validator error for query parameter array filter[id]=1

I have an issue validating the request parameters to filter the records recieved in the query string

   $validator = Validator::make($request->request->all(), [
            'filter' =>
                [
                 'array',
                 Rule::in(implode(',',$columns))
                ],
            'page' =>'integer'
        ]);

Where the coulmns include id, name, size etc. and the API request has the following format

./findAll?filter[id]=1&filter[name]=test

I want to return a 400 response when any filter is passed which does not exist as a column.

like image 994
samar Avatar asked May 10 '26 10:05

samar


1 Answers

You can use Validator extension to make your own validator:

In AppServiceProvider's put this code: (or in any provider)

public function boot(){
  Validator::extend('keys_in', function ($attribute, $value, $arr, $validator) {
      if (!is_array($value)) return false;

      foreach (array_keys($value) as $key) {
          if (!in_array($key, $arr)) return false;
      }

      return true;
  });

  Validator::extend('keys_in_columns', function ($attribute, $value, $table, $validator) {
      if (!is_array($value)) return false;

      $columns = Schema::getColumnListing($table);

      foreach (array_keys($value) as $key) {
          if (!in_array($key, $columns)) return false;
      }

      return true;
  });
}

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

Then in any controller you can use this two rules:

$validator = Validator::make($request->request->all(), [
    'filter' =>['array','keys_in:' . implode(',',$columns)],
    'page' =>'integer'
]);

Or use keys_in_columns shortcut which I defined above:

$validator = Validator::make($request->request->all(), [
    'filter' =>['array','keys_in_columns:users'],
    'page' =>'integer'
]);

don't forget to use use Illuminate\Support\Facades\Schema; and use Illuminate\Support\Facades\Validator; in Service Provider

Hope this helps you

like image 108
Malkhazi Dartsmelidze Avatar answered May 12 '26 11:05

Malkhazi Dartsmelidze