skip to Main Content

I am trying to get the new validated request after merging the request with new variable. It can be found in $request->all() but not in $request->validated(). I understand that the new variable doesnt not being validated with the request but is there anyway to get the new form request after merged?

Before Merge: dd($request->all());

array:2 [▼
  "Name" => "Jack"
  "Age"  => "12" 
]

Merge new variable with $request

$request->merge(['Fruit' => 'apple']);

After merge: dd($request->all());

array:3 [▼
  "Name" => "Jack"
  "Age"  => "12" 
  "Fruit"  => "Apple" 
]

After merge: dd($request->validated());

array:3 [▼
  "Name" => "Jack"
  "Age"  => "12" 
]

Request Rules

public function rules()
    {
        return [
            'Name' => 'nullable',
            'Age' => 'nullable',
            'Fruit' => 'nullable',
        ];
    }

3

Answers


  1. Add a request variable like this:

    $request->request->add(['Fruit' => 'apple']);
    
    Login or Signup to reply.
  2. You can use the method prepareForValidation, like this in your Request class:

    protected function prepareForValidation()
    {
        $this->merge([
            'Fruit' => 'Apple',
        ]);
    }
    
    Login or Signup to reply.
  3. <?php
    
    namespace AppHttpRequests;
    
    class RequestExample extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return auth()->check();
        }
    
        /**
         * @return Validator
         */
        protected function getValidatorInstance()
        {
            $this->modifyRequestExampleRecords();
            return parent::getValidatorInstance();
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'Name'  => 'nullable',
                'Age'   => 'nullable',
                'Fruit' => 'nullable',
            ];
        }
    
        /**
         * @return void
         */
        protected function modifyRequestExampleRecords(): void
        {
            $this->request->add([
                "Fruit" => "apple"
            ]);
        }
    }
    

    Pass RequestExample $request as your method parameter. And then write dd($request->validated()); or dd($request->all());. You will get the 3 properties as well. But please try to avoid $request->all();. Because, SQL injection can be occurred by using this. So better to use $request->validated(); everywhere.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search