Reputation: 329
If a user select in the form that he wants 2 tickets for the ticket type "ticket type 1" and 1 ticket for the "ticket type 2" the RegistrationController
receives this in the $request
:
array:2 [▼
"_token" => ""
"types" => array:2 [▼
"ticket type 1" => "2"
"ticket type 2" => "1"
]
]
But I want to have a rule "StoreTicketTypeQuantity" to validate the following context:
Each ticket type has a column minPerUser and a maxPerUser column in database.
For example, the TicketType table has the ticket type with name "ticket type 1" with the minPerUser value as "1" and the maxPerUser value as "4". So in the select menu the user can only select values between 1 and 4 for the ticket type "ticket type 1".
However, a user can introduce for example in the source code the quantity as "100" for the ticket type "ticket type 1", and this should result in a validate error.
Doubt:
Do you know how to in the StoreTicketTypeQuantity rule file get the dynamic values of the array to validate it?
TicketType Model:
class TicketType extends Model
{
protected $fillable = [
'name', 'price', 'minPerUser', 'maxPerUser','congress_id'
];
public function congress(){
return $this->belongsTo('App\Congress');
}
}
Rule file:
class TicketTypeQuantity implements Rule
{
public function __construct()
{
}
public function passes($attribute, $value)
{
}
public function message()
{
return 'The validation error message.';
}
}
Upvotes: 0
Views: 277
Reputation: 655
Validator::extend('numericarray', function($attribute, $value, $parameters)
{
foreach($value as $v) {
if(!is_int($v)) return false;
}
return true;
});
Use it :
$rules = array('someVar'=>'required|numericarray')
Upvotes: 1
Reputation: 1211
try this custom validation in TicketTypeQuantity class:
public function passes($attribute, $value)
{
foreach($value as $key=>$v){
$ticket = TicketType::where('name',$key)->first();
if ( $v < $ticket->minPerUser || $v > $ticket->maxPerUser)
return false;
}
return true;
}
now in the validation put
$request->validate([
'types' => ['required', 'array', new TicketTypeQuantity ],
]);
Upvotes: 1