Laravel 5.2:验证问题

时间:2016-05-07 07:36:33

标签: php laravel laravel-5.2

在我的控制器中:

$this->validate($request, [ 
     'name' => 'required',
]);

$tasks = new Task;

$tasks->name = $request->todo;
if($tasks->save()){
  $tasks->save();
  return back();
}

字段已填满,问题是验证程序仍然抛出错误: The name field is required

我错过了什么。

2 个答案:

答案 0 :(得分:1)

验证器验证REQUEST输入,而不验证您的模型。如果您的请求中有一个名为todo的字段,并且您希望将其设为必填字段,则可以执行以下操作:

$this->validate($request, [ 
     'todo' => 'required', // this is the name of the field from your form as it comes through to the Request object
]);

$task = new Task();
$task->name = $request->todo;

if($task->save()) { // note, you don't need to call save() twice
    return back();
}

// you probably want to do something here in case save fails?

答案 1 :(得分:0)

您需要将'name' => 'required'更改为'todo' => 'required',因为您需要指定在 FORM FIELD

中写入的名称

如果您在控制器中定义 RULES 时使用了<input type="text" name"todo" />,则需要使用“todo”,如下所示:

    $this->validate($request, [ 
     'todo' => 'required', 
    ]);

希望这会对你有所帮助。