如何在 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?
}

推荐答案

从 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']);

相关文章