型号:
protected $validationRules = [
'username' => 'required'
];
protected $validationMessages = [
'username' => [
'required' => 'Please enter a username'
]
];
控制器:
if($this->request->getMethod()== 'post'){
$usermodel = new AppModelsUsers;
$User = $usermodel
->where('username' , $this->request->getPost('username'))
->first();
if(!$User){
print_r($usermodel->errors());
/*return redirect()->to('/login')->with('errors' , $usermodel->errors())->withInput();*/
}
视图:
<?php if(session()->has('errors')): ?>
<div class="alert alert-warning">
<ul>
<?php foreach(session('errors') as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
我知道我已经把退货声明注释掉了。我在控制器中用print_r((得到了相同的空数组;return redirect with view"。
但是:如果我在控制器中手动指定闪烁消息,那么我得到了";错误的pw";消息:
if(!$UserFromDB){
return redirect()->to('/login')->with('errors' , array('Wrong pw'))->withInput();
/*print_r($usermodel->errors());*/
/*return redirect()->to('/login')->with('errors' , $usermodel->errors())->withInput();*/
}
我不认为我们在模型中使用表单验证,而是在控制器中使用。这就是我进行的方法
#Controller
if($this->request->getMethod()== 'post'){
$rules = ['username' => ['rules' => 'required];
$messages = ["username" => [
"required" => "Please enter a username",
],
];
if($this->validate($rules,$messages)){
// validation succeed
}
else{
// validation not ok
$response = [
'message' => $this->validator->getErrors()
];
$data['response'] = $response;
// redirect to your login view
}
}