laravel驗證(Validation)

在前端送資料到後端的時候
很多格式是有可能被串改的
因此在使用獲得的資料前
要先做驗證的動作
Laravel就有提供驗證的功能
https://laravel.com/docs/8.x/validation

直接舉例

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

將接收到的$request直接送入驗證
此程式碼驗證的有'phone','title','desc'

required 必填項目
unique:shop_infos,phone 在shop_infos資料表中的欄位phone必須為唯一
max 最大字數
min 最小字數

下半段就是不符合條件時回傳的訊息
(Laravel有預設的訊息,此為客製化訊息)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

頁面上要顯示錯誤訊息的區塊則放上這段程式碼

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

這個驗證功能有很多
在此小小舉例
詳細功能文件中都有詳述

tags: laravel