Laravel 5 Basics (11)-Form validation
In the creation of an article, if you do not enter a direct submission, OK, you get an empty article, without any error, this is not right. Run under the command line php artisan
to see an option make:request
to create a new form request class. Executing at the command line
php artisan make:request CreateArticleRequest
The generated files are in the app/http/requests
directory. In the file we can see two methods:
public function authorize(){return false;}public function rules(){return [//];}
authorize
Indicates whether the user needs to be an authenticated user when submitting the form, we do not need authentication and return true. rules
is our rule method. Let's modify this method:
public function authorize(){//修改为 true,表示不需要认证,或者是通过认证return true;}public function rules(){return ['title' => 'required|min:3', 'body' => 'required', 'published_at' => 'required|date'];}
Other constraints can be inserted into the laravel documentation. The above constraint representation must be title
entered, with a minimum of 3 characters, body
is required, published_at
is required, and is a date.
In the view, we can always access $errors
variables to determine if we have errors, modify the view
@if ($errors->any())
@foreach($errors->all() as $error)
- {{ $error }}
@endforeach
@endif {{--使用我们添加的 illuminate\html 开源库--}} {!! Form::open(['url' => 'articles']) !!}
Modify the controller to introduce our Request class.
public function store(Requests\CreateArticleRequest $request) { Article::create($request->all()); return redirect('articles'); }
Submit the form again, and you will see the error message.
Change message to Chinese
The error message displayed is in English, in fact laravel considering the internationalization of the problem, first modified config/app.php
,
'locale' => 'zh',
Set the locale language to Chinese, then resources/lang
create a new folder below zh
, copy the resources/lang/en/validation.php
file to the zh
directory, and modify:
"min" => ["numeric" => "The :attribute must be at least :min.","file" => "The :attribute must be at least :min kilobytes.","string" => ":attribute 至少要包含 :min 字符。","array" => "The :attribute must have at least :min items.",],"required" => ":attribute 必须填写。",
Others can be translated by themselves. Submit an empty form again, the error message is Chinese. And min:3
the judgment is at least 3 Chinese.
--
Laravel also integrates the methods in the controller validate
, in other words, we don't necessarily have to generate the request class, which we can do directly in the controller.
To modify a controller:
//注意 Request 的命名空间,不要弄错了 public function store(\Illuminate\Http\Request $request) { $this->validate($request, [ 'title' => 'required|min:3', 'body' => 'required', 'published_at' => 'required|date' ]); Article::create($request->all()); return redirect('articles'); }
The result is the same, so that simple validation can be done more quickly.