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)
我没有测试过这个,但它应该可以工作.
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
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)
只需从控制器返回:
return back()->withErrors('your error message');
Run Code Online (Sandbox Code Playgroud)
你可以试试定制的留言包
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)
对于 Laravel 5.8:
.
抛出异常的最简单方法是这样的:
throw new \ErrorException('Error found');
Run Code Online (Sandbox Code Playgroud)