Laravel-5合并多级表单阵列验证

时间:2015-07-24 16:11:36

标签: php arrays laravel laravel-5

我有一张我在Laravel-5中创建的表单。此表单包含输入数组。我还使用php artisan make:request ClassRequest创建了一个请求文件。在我的请求文件中,我添加了Laravel验证器()函数,用于在表单发布时向表单数组添加其他字段。

但是,我似乎无法以我想要的方式更新/合并表单数组。

查看文件:

<input type="text" name="class[0]['location_id']" value="1">
<input type="text" name="class[1]['location_id']" value="2">

请求文件(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());
    }

}

从上面的请求文件中可以看到,我正在尝试向表单数组添加新的键/值对(location =&gt;'test123')。但是,只有1个字段会被发布到控制器。

有谁知道这样做的正确方法?

1 个答案:

答案 0 :(得分:2)

合并 函数将给定数组合并到集合中,并且与集合中的字符串键匹配的数组中的任何字符串键都将 覆盖 集合中的值。这就是为什么你只看到1个字段发布到控制器。

 foreach($input as $key => $val)
        {
            $this->merge(['class' => [$key => [
                'location_id' => $input[$key]['location_id'],
                'location'  => 'test123'
                ]
            ]]);
        }

'class'密钥在每次迭代中被覆盖,并且只持续一个。所以唯一的项目是最后一个。

$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());

如果您收到与位置ID相关的错误,请尝试此

 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());
   }