aberrant's avatar

Form Request Get Only Fields with Validation Rules

I am using a form request to help with a form wizard where a user fills out fields across multiple steps. I'm trying to use a single form request for the store and the update. How can I get only the input fields that have validation rules? I've looked into request()->only() but you need to specify an array of form fields, when doing updates on my wizard a user only updates a single page at a time so the fields that I want to request would change for each page they update. Here's an example of my validation rules:

$rules = [];
        
        if ($this->current_step == 1 || $this->current_step == 3) {
            $rules += [
                'field_1'   => 'required',
                'field_2'   => 'required',
                'field_3'   => 'required'
            ];
        }

        if ($this->current_step == 2 || $this->current_step == 3) {
            $rules += [
                'field_4'   => 'required'
            ];
        }

        if ($this->current_step == 3) {
            $rules += [
                'field_5' => 'required'
            ];
        }
        
        return $rules;

If a user is updating just step 2 I want my request to only return field_4. Is there a method on the Request class to limit the fields just based on ones that have validation rules?

0 likes
4 replies
nnnayeem's avatar

You can validate checking the steps via checking url. Like:

if(step1URL){
    some validation rule
elseif(step2URL){
    some validation rule
}

You can get the url. Follow the laravel doc:

https://laravel.com/docs/5.7/routing#accessing-the-current-route
aberrant's avatar

Thanks, the problem isn't the validation, the problem is the request array returns all the fields passed to it regardless if they're in the validation rules or not. I'm trying to limit that array based just on fields which are under validation. I can manually do this with the only() function but then I have to explicitly list the fields that I want, I'm trying to find a better way by just using whatever fields are defined in the validation rules array.

aberrant's avatar

I figured it out in case anyone else is dealing with a similar issue.

If you use:

$request->validated(); 

instead of:

$request->all() 

you can retrieve just the fields that have been validated.

1 like

Please or to participate in this conversation.