[英]Input array validation message error Laravel 5.5
當其中之一輸入未成功通過驗證時,我試圖顯示帶有數組輸入的自定義驗證消息,因為Laravel默認顯示的錯誤是這樣的:
link.1的格式無效。
我想展示這樣的東西:
“值”的格式無效。
我讀到有一個稱為messages()
方法,可以在請求文件中覆蓋它:
BannerRequest.php
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class BannerRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"imagenes.*" => "nullable|mimes:jpeg,png,jpg|max:5120",
"links.*" => "nullable|string|max:191|url",
"idiomas.*" => "required|string|max:191",
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
$messages = array();
foreach($this->imagenes as $key => $valor) {
$messages[] = array('imagenes.'.$key.'.mimes:jpeg,png,jpg' => "La imagen ".$valor." no contiene un formato válido");
$messages[] = array('imagenes.'.$key.'.max:5120' => "La imagen ".$valor." no contiene un formato válido");
}
foreach($this->links as $key => $valor) {
$messages[] = array('links.'.$key.'.url' => "El link ".$valor." no es una URL válida");
}
return $messages;
}
}
根據文檔:
此方法應返回屬性/規則對及其相應錯誤消息的數組
因此,由於我正在處理輸入數組,因此我認為我應該遍歷它們,以便獲得它們的鍵以得到如下內容: link.0.validation_rule
然后link.1.validation_rule
,依此類推...
但是,如果執行此操作,則在顯示錯誤時,我的視圖會出現以下錯誤:
Array to string conversion
在line 247
上,該錯誤引發在vendor/laravel/framework/src/Illuminate/Support/MessageBag.php
上。
我在做什么錯?,因為Laravel在驗證輸入數組方面沒有提及太多。
完成后, messages()
方法應返回如下消息數組:
public function messages()
{
$messages = array();
foreach($this->imagenes as $key => $valor) {
$messages['imagenes.'.$key.'.mimes:jpeg,png,jpg'] = "La imagen ".$valor." no contiene un formato válido";
$messages['imagenes.'.$key.'.max:5120'] = "La imagen ".$valor." no contiene un formato válido";
}
foreach($this->links as $key => $valor) {
$messages['links.'.$key.'.url'] = "El link ".$valor." no es una URL válida";
}
return $messages;
}
我希望這對其他有相同疑問的人有所幫助,因為此處大多數類似的問題都沒有簡潔的答案。 如果對此有更好的答案,或者存在更干凈的方法,我將很高興閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.