2016-05-01 92 views
1

使用Laravel Form Request Validation
如何自定義響應格式

例如,它顯示錯誤信息爲: -Laravel請求確認消息格式化

{ 
    "password": ["The password field is required."], 
    "password_confirmation": ["The password confirmation field is required."] 
} 

我希望把所有的錯誤信息到描述屬性,有點像。

{ 
    "status" : false, 
    "description" : ["The password field is required.", "The password confirmation field is required."] 
} 

回答

0

它的正下方在您提供的文檔鏈接:

您可以通過 重寫消息的方法,通過定製的形式請求中使用的錯誤消息。此方法應該返回一個數組 屬性/規則對及其相應的錯誤消息。

所以,把這個在您的要求:

public function messages() 
{ 
    return [ 
     'password.required' => 'The password field is required.', 
     'password_confirmation.required' => 'The password confirmation field is required.', 
    ]; 
} 
0
public function rules() 
    { 

     return [ 
     'password' => [ 'required' , 'min:4','confirmed' ] , 
     'password_confirmation' => [ 'required' , 'min:4' ] 
      ]; 

    } 
0

另一種方法來創建自定義的驗證消息將自己的消息數組傳遞給你的控制器動作validate功能。 validate函數將自定義消息作爲第三個參數。

public function listing(Request $request) 
{ 
    $messages = [ 
     'search_input.alpha_dash' => 'Please enter a valid search term. Only use letters, dashes and underscores.', 
    ]; 

    $this->validate($request, [ 
     'search_input' => 'alpha_dash', 
    ], $messages); 


    return view('videos.index'); 
} 
0

撤出所有錯誤信息到一個數組,你需要做這樣的事情...

$validator = Validator::make($request->all(), [ 
    'password' => 'required', 
    'password_confirmation' => 'required|same:password', 
]); 

$messages = $validator->errors()->toArray(); 
/* ** This will give you something like this ** 
* 
*  'password' => 'The password field is required.', 
*  'password_confirmation' => 'The password confirmation field is required.' 
* 
* **/ 

// If you want only array values - as your example of description, then use php's array_values() method like this... 

$description_arr = array_values($messages); 

感謝希望這將幫助你.. !! 要更好地瞭解Laravel驗證,請通過其文檔 - Laravel Validation Docs