您必須將數據庫操作包裝到try-catch
塊中,並在出現錯誤時捕獲錯誤並執行其他操作,可能會使用錯誤消息重定向舊輸入數據。
duplicate entry的錯誤代碼是。所以如果你得到1062作爲錯誤代碼,這意味着這個數據是重複的條目。這裏是捕捉這個異常的代碼。
try {
$data = Model::create(array(
'templateURL' => 'some value ',
));
} catch (Illuminate\Database\QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
// we have a duplicate entry problem
}
}
或者,如果您不希望自己處理異常,您可以藉助Laravel Validator。就像在你的視圖模板在你的控制器以下
// validation rules
$rules = array(
'templateURL' => 'unique:YourTableNameHere'
);
$validator = Validator::make(Input::all(), $rules);
// check if the validation failed
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect user back to the form with the errors from the validator
return Redirect::to('form')
->withErrors($validator);
} else {
// validation successful
$data = Model::create(array(
'templateURL' => 'some value ',
));
}
然後你就可以通過$errors
變量訪問的錯誤消息。 瞭解更多關於那裏驗證https://laravel.com/docs/5.3/validation
閱讀此https://scotch.io/tutorials/laravel-form-validation – shoieb0101
@ shoieb0101你的意思是與'$規則'的東西?看起來不錯,但我也可以把它放在我的控制器中,我必須像他那樣把它放在我的路線上? – user5638730
您可以將您的驗證規則放入您的控制器或使用formRequest進行驗證。 https://laravel.com/docs/5.2/validation#form-request-validation – shoieb0101