Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

meeshka's avatar

Form Request Validation and controller

Hi,

I have the following controller method to handle a http POST.

    public function orderSubmit(CheckoutOrderRequest $request)
    {
    // I would like to perform a few other checks here 
    // and if one of them fails, add errors to validator 
    // and redirect back to original form where request came from
    }

Is there a way to invoke/access the validator via $request and add errors like below:

$validator->errors()->add('field', 'Something is wrong with this field!');
0 likes
1 reply
dharmendrajadon's avatar

You can extend validator class and can have your custom validations. Use the custom validations like the other validation checks of validator class.

Create a file and have contents like:

    <?php

    /* @var \Illuminate\Validation\Factory $validator */

    $validator->extend(
'valid_password',
function ($attribute, $value, $parameters)
{
    return preg_match('/^[a-zA-Z0-9!@#$%\/\^&\*\(\)\-_\+\=\|\[\]{}\\\\?\.,<>`\'":;]+$/u', $value);
}
    );

    $validator->extend(
'phone_number',
function ($attribute, $value, $parameters)
{
    return strlen(preg_replace('#^.*([0-9]{3})[^0-9]*([0-9]{3})[^0-9]*([0-9]{4})$#', '$1$2$3', $value)) == 10;
}
    );

And then in your AppServiceProvider (or any registered provider):

    public function boot(Factory $validator)
{
    require_once app_path() . '/validators.php';
}

Then your validation rule would be:

    public function rules()
{
    return [
        'phone' => ['required','phone_number']
    ];
}

Please or to participate in this conversation.