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

Svi*_*ish 41 php validation error-handling exception laravel

有一种方法可以将CSV数据导入数据库.我使用了一些基本的验证

class CsvImportController extends Controller
{
    public function import(Request $request)
    {   
        $this->validate($request, [
            'csv_file' => 'required|mimes:csv,txt',
        ]);
Run Code Online (Sandbox Code Playgroud)

但之后事情可能会因为更复杂的原因而出错,在兔子洞的下方,会抛出某种异常.我不能在validate这里使用这个方法编写适当的验证内容,但是,我真的很喜欢Laravel在验证失败时如何工作以及将错误嵌入到刀片视图等中是多么容易,所以...

是否有一种(最好是干净的)手动告诉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?
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rin 97

从laravel 5.5开始,ValidationException该类有一个静态方法withMessages,您可以使用:

$error = \Illuminate\Validation\ValidationException::withMessages([
   'field_name_1' => ['Validation Message #1'],
   'field_name_2' => ['Validation Message #2'],
]);
throw $error;
Run Code Online (Sandbox Code Playgroud)

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

  • 它是almos,而不是一个简单的数组,它是一个多维数组,这个工作```$ error = ValidationException :: withMessages(["one_thing"=> ["Validation Message#1"],"another_thing" => ['验证消息#2']]); ``` (3认同)
  • 啊!*确实*有效,并且还删除了帮助方法的"需要",以删除丑陋的messagebag内容.谢谢! (2认同)

Mār*_*dis 17

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

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


Has*_*him 17

在 Laravel 8 及更高版本中,以下内容在控制器和模型中均有效:

return back()->withErrors(["email" => "Are you sure the email is correct?"])->withInput();
Run Code Online (Sandbox Code Playgroud)

这将使用户返回到之前所在的视图,显示指定字段的指定错误(如果存在),并使用用户刚刚输入的信息重新填充所有字段,从而允许他们简单地调整不正确的字段而不是再次填写整个表格。

另一种功能类似的替代方案是执行以下操作:

throw ValidationException::withMessages(['email' => 'Are you sure the email is correct?']);
Run Code Online (Sandbox Code Playgroud)


Man*_*s D 7

只需从控制器返回:

return back()->withErrors('your error message');
Run Code Online (Sandbox Code Playgroud)

  • 添加withInput(),像这样return back()-&gt; withErrors('error')-&gt; withInput(); (4认同)
  • 最佳答案(不要忘记 `withInput()` (2认同)

mad*_*scu 6

你可以试试定制的留言包

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()]));
}
Run Code Online (Sandbox Code Playgroud)


Sya*_*ien 6

对于 Laravel 5.8:

.

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

throw new \ErrorException('Error found');
Run Code Online (Sandbox Code Playgroud)

  • 请解释这将如何处理验证错误? (3认同)