【问题标题】:Laravel-5 merge multi-level form array validationLaravel-5 合并多级表单数组验证
【发布时间】:2015-10-15 09:37:11
【问题描述】:

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

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

查看文件:

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

}

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

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

【问题讨论】:

  • 你能再解析一些代码吗? $this 是什么? $key 是什么?期望的结果是什么?
  • 对不起,这行代码存在于 laravel 请求文件的 validator() 函数中。

标签: php arrays laravel laravel-5


【解决方案1】:

Merge 函数将给定的数组合并到集合中,并且数组中与集合中的字符串键匹配的任何字符串键将覆盖 集合中的值。所以这就是为什么您只看到 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());
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2016-02-28
    • 2016-02-15
    相关资源
    最近更新 更多