How to manually add new values in laravel request object
I am trying to add some new value in my laravel request object when sending request from laravel form.
Generally when we are sending some data using form it will receive by laravel controller using $request->all();
suppose
1 2 3 4 5 |
<form name="test" method="post" action="/test/test-action"> Name <input type="text" name="name" value="Jhon"> <br> Fathers Name <input type="text" name="f_name" value="Michel"> <br> Mothers Name <input type="text" name="m_name" value="Rebeka"> <br> </form> |
In controller function we have received bellow data;
1 2 3 4 5 6 7 8 9 |
dd($request->all()); array:5 [ "_method" => "POST" "_token" => "q8Qw83anwExn2TKFd3jgPKD2VRpvQmt9wTu7kGlY" "name" => "Jhon" "f_name" => "Michel" "m_name" => "Rebeka" ] |
But sometimes we need to add some extra field in request for different kind of reason. One of the most important reason is data validation or data modification.
Suppose in your model there is a field named “age” and you want to make a validation rules that age can not be more then 60 and less then 5 and required. Also the age field is not coming from frontend test from.
You have a validation rules like
1 2 3 4 5 6 |
$rules = [ 'name' => 'required', 'f_name' => 'required', 'm_name' => 'required', 'age' => 'required|min:5|max:60', ]; |
Then what happened when you pass $request object to your validation rules?
Validation rules returns a validation error and that is “age field is required”. Coz in $request object there is no age field. So you have to add age field in $request object. This is so simple solution and not so big deal.
Just add this age field with value using an array in $request object like as bellow
1 2 3 |
$request->request->add(['age'=>30]); dd($request->all()); |
You will get this data in dump section
1 2 3 4 5 6 7 8 |
array:6 [ "_method" => "POST" "_token" => "q8Qw83anwExn2TKFd3jgPKD2VRpvQmt9wTu7kGlY" "name" => "Jhon" "f_name" => "Michel" "m_name" => "Rebeka" "age" => 30 ] |
So now you can easily pass $request object in validation rules. And there will not getting any validation error.
Recent Comments