如何为laravel验证而不是数字键设置自定义属性?

时间:2014-12-22 09:17:58

标签: php validation laravel laravel-4

如何发送laravel验证的值?

$data = explode(",", trim(Input::get('Vehicle_Data')));  //exploding data
$rule  =  array(
$data[0] => 'required',
$data[1] => 'required',
$data[2] => 'required|email|unique:users'
              ) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
   {
    $messages = $validator->messages();
    return $messages;
    }
else
    {
    return 'ok'
    }

我只想检查$ data [0]是否必需且应该是唯一的

时效果很好
'email' => 'required|email|unique:users'

时无法正常工作
$data[2] => 'required|email|unique:users'

但是我不想将$ data [2]声明为另一个变量并且如何在不将数据[2]分配给另一个变量的情况下执行此操作

如果我确认它正在返回

Object {32: Array[1], 43: Array[1]}
控制台中的

1 个答案:

答案 0 :(得分:2)

以你尝试的方式做这件事可能不是最好的主意,但这就是你如何达到你想要的目标:

$data = explode(",", trim(Input::get('Vehicle_Data')));  //exploding data

$rules = array(
   'required',
   'required',
   'required|email|unique:users,email'
);

$data将是带有数字键的简单数组,因此$rules数组应该是相同的并且它将起作用。


编辑:根据评论,Validator::make能够 1 设置自定义消息, 2 设置自定义属性。所以对你而言,后者是要走的路:

$messages = []; // no need to specify that, unless you'd like
$attributes = ['id', 'name', 'email', ...]; // use your actual fields here

$validator = Validator::make($data, $rules, $messages, $attributes);

// then the messages will use $attributes array, so will show:
'The name has already been taken'
'The email field is required'

// instead of:
'The 1 has already been taken'
'The 2 field is required'