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.
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;anduse Illuminate\Support\Facades\Validator;in Service Provider
Hope this helps you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With