10.
表單驗證及錯誤處理
- 完整驗證說明:https://laravel-china.org/docs/laravel/5.6/validation/1302#189a36
- 編輯控制器
/專案/app/Http/Controllers/ExamController.php
,修改儲存方法:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|min:2|max:255',
]);
Exam::create($request->all());
return redirect()->route('exam.index');
}
-
接著修改/專案/resources/views/exam/create.blade.php
樣板檔,當有錯誤的時候顯示出來:
@if (count($errors) > 0)
@component('bs::alert', ['type' => 'danger'])
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endcomponent
@endif
-
如此就可以測試看看了!
-
若發現沒有中文訊息,可以直接將\專案\vendor\caouecs\laravel-lang\src\zh-TW\
整個目錄複製到\專案\resources\lang\
底下
cp -R vendor\caouecs\laravel-lang\src\zh-TW resources\lang\
-
若是想自己加上屬於自己的訊息,那可以這樣做:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|min:2|max:255',
], [
'required' => '「:attribute」為必填欄位',
'min' => '「:attribute」至少要 :min 個字',
'max' => '「:attribute」最多只能 :max 個字',
]);
Exam::create($request->all());
return redirect()->route('exam.index');
}
- 其中
:attribute
會帶出有錯誤的表單元件的name,如此,會比較清楚是哪個欄位沒填好。
- 關於錯誤處理可以參考:https://laravel-china.org/docs/laravel/5.6/validation/1302#working-with-error-messages