Have a method that's importing CSV-data into a Database. I do some basic validation using
有一種方法可以將CSV數據導入數據庫。我做了一些基本的驗證
class CsvImportController extends Controller
{
public function import(Request $request)
{
$this->validate($request, [
'csv_file' => 'required|mimes:csv,txt',
]);
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在驗證失敗時的工作方式以及將錯誤嵌入到刀片視圖等中是多么容易,所以...
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?
是否有一種(最好是干凈的)手動告訴Laravel“我知道我現在沒有使用你的驗證方法,但我真的希望你在這里公開這個錯誤,好像我做了”?有什么東西可以歸還,我可以用東西包裝,或者其他東西嗎?
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?
}
4 个解决方案
#1
36
從laravel 5.5開始,ValidationException類有一個靜態方法withMessages,你可以使用它:
$error = \Illuminate\Validation\ValidationException::withMessages([
'field_name_1' => ['Validation Message #1'],
'field_name_2' => ['Validation Message #2'],
]);
throw $error;
I haven't tested this, but it should work.
我沒有測試過這個,但它應該可以工作。
#2
2
Simply return from controller:
只需從控制器返回:
return back()->withErrors('your error message');
#3
1
you can try a custom message bag
你可以嘗試一個自定義的消息包
try
{
// Call the rabbit hole of an import method
}
catch(\Exception $e)
{
return redirect()->to('dashboard')->withErrors(new \Illuminate\Support\MessageBag(['catch_exception'=>$e]));
}
#4
1
Laravel <= 5.6 this solution worked for me:
Laravel <= 5.6這個解決方案對我有用:
$validator = Validator::make([], []); // Empty data and rules fields
$validator->errors()->add('fieldName', 'This is the error message');
throw new ValidationException($validator);