5.10 添加数据验证
最后更新于:2022-04-01 01:17:41
在 app/controllers/ArticlesController.php 文件中,修改 ArticlesController 控制器 store 动作:
~~~
public function store()
{
$rules = array('title' => 'required|min:5');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::route('articles.create')
->withErrors($validator)
->withInput();
}
$article = Article::create(array('title'=>Input::get('title'), 'text'=>Input::get('text')));
return Redirect::route('articles.show', array($article->id));
}
~~~
然后修改 app/views/articles/create.blade.php 添加 :
~~~
@if ($errors->any())
<div id="error_explanation">
<h2>{{ count($errors->all()) }} prohibited
this article from being saved:</h2>
<ul>
@foreach ($errors->all() as $message)
<li>{{ $message }}</li>
@endforeach
</ul>
</div>
@endif
~~~
再次访问 http://localhost:8000/articles/create ,尝试发布一篇没有标题的文章,会看到一个很有用的错误提示。