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',
];
}
CodePudding user response:
Add a request variable like this:
$request->request->add(['Fruit' => 'apple']);
CodePudding user response:
You can use the method prepareForValidation
, like this in your Request class:
protected function prepareForValidation()
{
$this->merge([
'Fruit' => 'Apple',
]);
}
CodePudding user response:
<?php
namespace App\Http\Requests;
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.
Have a good day.