:::

10. 表單驗證及錯誤處理

  1. 完整驗證說明:https://laravel-china.org/docs/laravel/5.6/validation/1302#189a36
  2. 編輯控制器 /專案/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');
    }
  3. 接著修改/專案/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
  4. 如此就可以測試看看了!

  5. 若發現沒有中文訊息,可以直接將\專案\vendor\caouecs\laravel-lang\src\zh-TW\整個目錄複製到\專案\resources\lang\底下

    cp -R vendor\caouecs\laravel-lang\src\zh-TW resources\lang\
  6. 若是想自己加上屬於自己的訊息,那可以這樣做:

    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');
    }
  7. 其中:attribute會帶出有錯誤的表單元件的name,如此,會比較清楚是哪個欄位沒填好。
  8. 關於錯誤處理可以參考:https://laravel-china.org/docs/laravel/5.6/validation/1302#working-with-error-messages

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D37%26tbdsn%3D1170

計數器

今天: 1257125712571257
昨天: 2299229922992299
總計: 7987652798765279876527987652798765279876527987652