php 如何在 Laravel 中手动返回或抛出验证错误/异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47219542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:33:05  来源:igfitidea点击:

How can I manually return or throw a validation error/exception in Laravel?

phplaravelvalidationexceptionerror-handling

提问by Svish

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 validatemethod 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...

但在那之后,由于更复杂的原因,事情可能会出错,更深入的兔子洞,会引发某种异常。我无法编写正确的验证内容来使用validate这里的方法,但是,我真的很喜欢 Laravel 在验证失败时的工作方式以及将错误嵌入到刀片视图等中是多么容易,所以......

Is there a (preferably clean) way to manuallytell Laravel that "I know I didn't use your validatemethod 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“我知道我validate现在没有使用你的方法,但我真的希望你在这里公开这个错误,就像我一样”?有什么我可以返回的东西,一个我可以用它包装东西的例外,或者什么?

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?
}

回答by Erin

As of laravel 5.5, the ValidationExceptionclass has a static method withMessagesthat you can use:

从 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.

我还没有测试过这个,但它应该可以工作。

Update

更新

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

回答by Mārti?? Briedis

Laravel <= 6.2this solution worked for me:

Laravel <= 6.2这个解决方案对我有用

$validator = Validator::make([], []); // Empty data and rules fields
$validator->errors()->add('fieldName', 'This is the error message');
throw new ValidationException($validator);

回答by Mantas D

Simply return from controller:

只需从控制器返回:

return back()->withErrors('your error message');

回答by madalinivascu

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->getMessage()]));
}

回答by Syamsoul Azrien

For Laravel 5.8:

对于 Laravel 5.8:

.

.

The easiest way to throw an exception is like this:

抛出异常的最简单方法是这样的:

throw new \ErrorException('Error found');

回答by hashem sheikhypour

i just add

我只是补充

/** * @throws \Illuminate\Validation\ValidationException */

/** * @throws \Illuminate\Validation\ValidationException */

and fix

并修复