且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-24 03:07:07

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