Search code examples
phplaravel

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


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'));//returns null and deprecated
        error_log($this->request->input('section')); //this is absolutely wrong but I tried it anyways
        error_log($this->request->section);  // returns null
        error_log($this->section);           // returns 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 what's wrong


Solution

  • 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?