Home > Mobile >  Laravel validation - Different Attributes Specifications
Laravel validation - Different Attributes Specifications

Time:09-14

I'm using a LaravelMiddleware, which should check for Access. Therefore, I check for a specific Attributes, which sometimes have different names.

EG:

  1. $request->key
  2. $request->moduleKey

Im asking if there is a possiblitiy to check for 2 different attributes specifications?

Like so:

$data = $request->validate([
   'key|moduleKey' => ['required', 'numeric'],   
]);

CodePudding user response:

It's not possible this way, but you have 2 other options:

Validation

https://laravel.com/docs/9.x/validation#rule-required-without

$data = $request->validate([
   'key' => ['required_without:moduleKey', 'numeric'],   
   'moduleKey' => ['required_without:key', 'numeric'],   
]);

but the problem is you still dont know which one you need unless you always get them both: $data['key'] ?? $data['moduleKey']

You can also update the request beforenhand:

$request['key'] = $request['key'] ?? $request['moduleKey'];
$data = $request->validate([rules]);

this code above you could put in a middleware to make sure every request always have the "key" variable in the request.

  • Related