Home > Software engineering >  How to access request payload/post data inside rules() function - Laravel Form Request
How to access request payload/post data inside rules() function - Laravel Form Request

Time:04-07

I am trying to access a data called "section" in my rules() function inside my FormRequest Validator Class. What I am trying to do is check what is the value of "section" and return different rules. But apparently, I am not able to access the value of the data/payload.

I have checked the answer from here, but it didn't work for me : Laravel Form Request Validation with switch statement

Here is my code :

FormController.php

class FormController extends Controller
{
public function verify(DynamicFormRequest $request , $section)
  {
      return response()->json(['success' => 'everything is ok']); 
  }
}

DynamicFormRequest.php

class DynamicFormRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        error_log($this->request->get('section'));//retruns null and depricated
        error_log($this->request->input('section')); //this is absolutely wronge but , i tried it anyways
        error_log($this->request->section); //retruns null
        error_log($this->section); //retruns null
        switch ($this->request->get('section')) {
            case '1':
                return [
                    'item_name' => 'required',

                ];
                break;
            case 'Type2':
                return [ 
                    'item_favorite' => 'required',
                ];
                break; 
        }
    }
}

Please help to make me understand whats wronge

CodePudding user response:

you can use required_if:anotherfield,value to check the value for other fields

return [
  'item_name' => 'required_if:section,1',
  'item_favorite' => 'required_if:section,Type2'
]

https://laravel.com/docs/9.x/validation#rule-required-if

I hope it's helpful

CodePudding user response:

If you are using route model binding you can use $this->section right off the bat.

So this should work assuming your routes are set up in the correct format:

 error_log($this->section);

Route (Something like....):

  Route::post('section/{section}', [SectionController::class, 'update']);

This question could help: Stack Q: Laravel: Access Model instance in Form Request when using Route/Model binding

Lastly, Hard to know it's working without your other code. Have you dumped out $request to check section is in there?

  • Related