Laravel-5 bundles multilevel validation of an array of forms
I have a form that I created in Laravel-5. This form contains input arrays. I also created a request file using php artisan make:request ClassRequest
. In my request file, I added a Laravel validator () function that I use to add additional fields to the form array when the form is submitted.
However, I cannot get the form array to update / merge in the way I would like.
View file:
<input type="text" name="class[0]['location_id']" value="1">
<input type="text" name="class[1]['location_id']" value="2">
Request file (ClassRequest.php):
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\Factory as ValidatorFactory;
use DB;
class ClassRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function validator(ValidatorFactory $factory)
{
$input = $this->get('class');
foreach($input as $key => $val)
{
$dateInString = strtotime(str_replace('/', '-', $input[$key]['date']));
$this->merge(['class' => [$key => [
'location_id' => $input[$key]['location_id'],
'location' => 'test123'
]
]]);
}
return $factory->make($this->input(), $this->rules(), $this->messages());
}
}
As you can see from the request file above, I am trying to add a new key / value pair to the form array (location => 'test123'). However, only 1 field is ever sent to the controller.
Does anyone know the correct way to do this?
source to share
The Merge function merges the given array into a collection, and any string key in the array that matches a string key in the collection will overwrite the value in the collection. Therefore, you only saw 1 field sent through the controller.
foreach($input as $key => $val)
{
$this->merge(['class' => [$key => [
'location_id' => $input[$key]['location_id'],
'location' => 'test123'
]
]]);
}
'class'
the key is overwritten at each iteration and only the last one is saved. Thus, the only element is the last one.
$input = $this->get('class');
foreach($input as $key => $val)
{
$another[$key]['location_id']=$input[$key]["'location_id'"];
$another[$key]['location']='123';
}
$myreal['class']=$another;
$this->merge($myreal);
return $factory->make($this->input(), $this->rules(), $this->messages());
If you are getting error related to location id try this
public function validator(ValidatorFactory $factory)
{
$input = $this->get('class');
foreach($input as $key => $val)
{
foreach($input[$key] as $v){
$another[$key]['location_id']=$v;
$another[$key]['location']='124';
}
}
$myreal['class']=$another;
$this->merge($myreal);
return $factory->make($this->input(), $this->rules(), $this->messages());
}
source to share