如何確認 request body的參數是符合我們預期的?
除了透過資料庫的欄位設定之外,Laravel有個 ValidatesRequests trait 提供眾多驗證機制來避免寫入錯誤的資料。
$validator = Validator::make($request->all(), [
'user_id' => 'required',
'content' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors()->all();
$msg = $messages[0];
return response()->json(['success_code' => 401, 'response_code' => 0, 'response_message' => $msg]);
}
記得要先有 use Illuminate\Validation\ValidationException;
try {
$rules = [ "user_id" => "required|integer","content" => "required|string" ];
$message = [ "user_id.required" => "請輸入id","content.required" => "請輸入文章內容" ];
$request->validate($rules, $message)
} catch (ValidationException $exception) {
$errorMessage =$exception->validator->getMessageBag()->getMessages();
return $errorMessage;
}
public function registerAPI(Request $request)
{
try {
$rules = [
"name" => "required|string | between:1,10 ",
"email" => "required| email | unique:users,email",
"password" => "required|string| between:6,12 | regex:/^[A-Za-z0-9]+$/",
];
$message = [ // 欄位名稱.驗證方法名稱
"name.required" => "請輸入名稱",
"email.required" => "請輸入email",
"password.required" => "請輸入密碼",
"email.email" => "email格式錯誤",
"email.unique" => "email已使用",
"name.between" => "name 字數需6~12",
"password.regex" => "請勿輸入特殊符號",
];
$validResult = $request->validate($rules, $message);
} catch (ValidationException $exception) {
$errorObject = $exception->validator->getMessageBag()->getMessages();
$errorMessage = '';
foreach($errorObject as $key => $value) {
$errorMessage = $value[0];
}
return response()->json(['message' => $errorMessage], 201);
}
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
]);
return response()->json(['message' => 'register success , please login '], 201);
rules裡頭可以放各種官方文件有提到驗證機制,個人常用的如下:
message可針對rules設定回覆內容,沒設定系統會有預定的回覆訊息。
有遇到request欄位錯誤,就會產生這樣的錯誤內容。
可提供前端顯示錯誤訊息或是後端自我檢查錯誤狀況。
參考資料
https://docs.laravel-dojo.com/laravel/5.5/validation
https://laravel.com/docs/7.x/validation
https://stackoverflow.com/questions/47219542/how-can-i-manually-return-or-throw-a-validation-error-exception-in-laravel
https://hackmd.io/@8irD0FCGSQqckvMnLpAmzw/HJ1LqggUQ?type=view
https://laracasts.com/discuss/channels/laravel/get-the-message-in-validationexception