如何在Laravel中手动返回或引发验证错误/异常? [英] How can I manually return or throw a validation error/exception in Laravel?
问题描述
具有将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?
}
推荐答案
As of laravel 5.5, the ValidationException
class has a static method withMessages
that you can use:
$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.
更新
消息不必包装在数组中.您也可以这样做:
The message does not have to be wrapped in an array. You can also do:
use Illuminate\Validation\ValidationException;
throw ValidationException::withMessages(['field_name' => 'This value is incorrect']);
这篇关于如何在Laravel中手动返回或引发验证错误/异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!