有一种方法可以将CSV数据导入数据库。我使用
进行一些基本的验证class CsvImportController extends Controller
{
public function import(Request $request)
{
$this->validate($request, [
'csv_file' => 'required|mimes:csv,txt',
]);
但之后事情可能会因为更复杂的原因而出错,在兔子洞的下方,会引发某种异常。我无法在此处使用validate
方法编写适当的验证内容,但是,我非常喜欢Laravel在验证失败时的工作原理以及将错误嵌入到刀片视图中的难易程度等等,所以......
是否有一种(最好是干净的)手动告诉Laravel的方式"我知道我现在没有使用你的validate
方法,但我&#39 ; d真的很喜欢你在这里公开这个错误,好像我做了#34;?有什么东西可以归还,我可以用东西包装,或者其他东西吗?
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?
}
答案 0 :(得分:77)
从laravel 5.5开始,您可以使用ValidationException
class has a static method withMessages
:
$error = \Illuminate\Validation\ValidationException::withMessages([
'field_name_1' => ['Validation Message #1'],
'field_name_2' => ['Validation Message #2'],
]);
throw $error;
我还没有对此进行测试,但它应该有效。
答案 1 :(得分:9)
Laravel< = 5.6 这个解决方案适合我:
$validator = Validator::make([], []); // Empty data and rules fields
$validator->errors()->add('fieldName', 'This is the error message');
throw new ValidationException($validator);
答案 2 :(得分:6)
只需从控制器返回:
return back()->withErrors('your error message');
答案 3 :(得分:2)
您可以尝试自定义消息包
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 :(得分:0)
对于Laravel 5.8:
。
引发异常的最简单方法是这样的:
throw new \ErrorException('Error found');
答案 5 :(得分:0)
我只需添加
/ ** * @throws \ Illuminate \ Validation \ ValidationException * /
并修复