Form Requests - Prepare for Validation

Ariel Mejia

June 9st, 2021 - 1 min read

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

Create a custom rule to validate the account

php artisan make:rule AccountHasAPaidPlanRule

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.';
}

Make a form request

php artisan make:request FeatureRequest

Using PrepareForValidation

// 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!


Ariel Mejia Illustration

Ariel Mejia

Laravel Senior Developer

Engineer with 7+ years of experience working in backend & frontend technologies
Open Source Maintainer of packages for Laravel community.

Stay up with Laravel

Sign up & get tips and tricks

You'll get monthly updates regarding my most recent articles and products.