php throw or return,如何在Laravel中手動返回或拋出驗證錯誤/異常?

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 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在驗證失敗時的工作方式以及將錯誤嵌入到刀片視圖等中是多么容易,所以...

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?

是否有一種(最好是干凈的)手動告訴Laravel“我知道我現在沒有使用你的驗證方法,但我真的希望你在這里公開這個錯誤,好像我做了”?有什么東西可以歸還,我可以用東西包裝,或者其他東西嗎?

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?

}

4 个解决方案

#1

36

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

我沒有測試過這個,但它應該可以工作。

#2

2

Simply return from controller:

只需從控制器返回:

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

#3

1

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

}

#4

1

Laravel <= 5.6 this solution worked for me:

Laravel <= 5.6這個解決方案對我有用:

$validator = Validator::make([], []); // Empty data and rules fields

$validator->errors()->add('fieldName', 'This is the error message');

throw new ValidationException($validator);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值