Sometimes is necessary to compute/get
a value based on a request
and then apply form request validation on it
Let's imagine that is required to validate if a user->account->hasPaidPlanAccount()
, but the route only has the /{user}
param
php artisan make:rule AccountHasAPaidPlanRule
In our custom rule we can fetch our Account
model based on account_id
value from a request
,
an input that is not present in the request
public function passes($attribute, $account_id)
{
/** @var Account */
$account = Account::findOrFail($account_id);
return $account->hasPaidPlan();
}
public function message()
{
return 'The feature requires a paid plan.';
}
php artisan make:request FeatureRequest
// add the account_id as a request input
public function prepareForValidation()
{
$this->merge([
'account_id' => $this->route('user')->account_id,
]);
}
public function rules()
{
return [
'account_id' => [new AccountHasAPaidPlanRule]
];
}
Our custom rule does not depend on request
account_id
presence, so it can be used when request
has it or not without issues.
Thanks for reading!
Sign up & get tips and tricks
You'll get monthly updates regarding my most recent articles and products.