PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

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

 April 19, 2022     laravel, php     No comments   

Issue

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


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?



Answered By - KayleeGrace
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing