問題描述
有一種將 CSV 數據導入數據庫的方法.我使用
Have a method that's importing CSV-data into a Database. I do some basic validation using
class CsvImportController extends Controller
{
public function import(Request $request)
{
$this->validate($request, [
'csv_file' => 'required|mimes:csv,txt',
]);
但在那之后,由于更復雜的原因,事情可能會出錯,更深入的兔子洞,會引發某種異常.我無法在這里編寫與 validate
方法一起使用的正確驗證內容,但是,我真的很喜歡 Laravel 在驗證失敗時的工作方式以及將錯誤嵌入到刀片中是多么容易查看等,所以...
But after that things can go wrong for more complex reasons, further down the rabbit hole, that throws exceptions of some sort. I can't write proper validation stuff to use with the validate
method here, but, I really like how Laravel works when the validation fails and how easy it is to embed the error(s) into the blade view etc, so...
是否有一種(最好是干凈的)方法可以手動告訴 Laravel我知道我現在沒有使用你的 validate
方法,但我真的很喜歡你像我一樣在這里公開這個錯誤"?有什么我可以返回的東西,一個可以用來包裝東西的例外,或者什么?
Is there a (preferably clean) way to manually tell Laravel that "I know I didn't use your validate
method right now, but I'd really like you to expose this error here as if I did"? Is there something I can return, an exception I can wrap things with, or something?
try
{
// Call the rabbit hole of an import method
}
catch(Exception $e)
{
// Can I return/throw something that to Laravel looks
// like a validation error and acts accordingly here?
}
推薦答案
從 laravel 5.5 開始,ValidationException
類有一個靜態方法 withMessages
您可以使用:
As of laravel 5.5, the ValidationException
class has a static method withMessages
that you can use:
$error = IlluminateValidationValidationException::withMessages([
'field_name_1' => ['Validation Message #1'],
'field_name_2' => ['Validation Message #2'],
]);
throw $error;
我還沒有測試過這個,但它應該可以工作.
I haven't tested this, but it should work.
更新
消息不必包裝在數組中.你也可以這樣做:
The message does not have to be wrapped in an array. You can also do:
use IlluminateValidationValidationException;
throw ValidationException::withMessages(['field_name' => 'This value is incorrect']);
這篇關于如何在 Laravel 中手動返回或拋出驗證錯誤/異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!