2015-05-29 85 views
6

我有一個表單請求來驗證註冊數據。該應用程序是一個移動API,我希望這個類在驗證失敗的情況下返回格式化的JSON,而不是默認情況下(重定向)。Laravel 5更改表單請求失敗驗證行爲

我試圖覆蓋從Illuminate\Foundation\Http\FormRequest類的方法failedValidation。但這似乎並不奏效。有任何想法嗎?

代碼:

<?php 

namespace App\Http\Requests; 

use App\Http\Requests\Request; 
use Illuminate\Contracts\Validation\Validator; 

class RegisterFormRequest extends Request { 

/** 
* 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 [ 
     'email' => 'email|required|unique:users', 
     'password' => 'required|min:6', 
    ]; 
} 

} 
+2

請發表您的代碼的人來檢查。 – SuperBiasedMan

+0

我猜你正在通過AJAX調用你的API?你可以強制API調用期望從你的API的JSON?在jQuery中,它看起來像這樣:$ .getJSON。 – ChainList

回答

1

通過查看Illuminate\Foundation\Http\FormRequest下面的函數,它似乎Laravel正確處理它。

/** 
    * Get the proper failed validation response for the request. 
    * 
    * @param array $errors 
    * @return \Symfony\Component\HttpFoundation\Response 
    */ 
    public function response(array $errors) 
    { 
     if ($this->ajax() || $this->wantsJson()) 
     { 
      return new JsonResponse($errors, 422); 
     } 

     return $this->redirector->to($this->getRedirectUrl()) 
             ->withInput($this->except($this->dontFlash)) 
             ->withErrors($errors, $this->errorBag); 
    } 

而且按照wantsJson功能在下面Illuminate\Http\Request,你必須明確地尋求JSON響應,

/** 
    * Determine if the current request is asking for JSON in return. 
    * 
    * @return bool 
    */ 
    public function wantsJson() 
    { 
     $acceptable = $this->getAcceptableContentTypes(); 

     return isset($acceptable[0]) && $acceptable[0] == 'application/json'; 
    } 
0

這是我的解決方案,它是在我結束工作良好。我添加了下面的功能請求代碼:

public function response(array $errors) 
{ 
    if ($this->ajax() || $this->wantsJson()) 
    { 
     return Response::json($errors); 
    } 

    return $this->redirector->to($this->getRedirectUrl()) 
            ->withInput($this->except($this->dontFlash)) 
            ->withErrors($errors, $this->errorBag); 
} 

響應函數可以很好地處理laravel。它會自動返回,如果你請求json或ajax。

4

無需覆蓋任何功能。只需添加

Accept: application/json 

在您的表單標題中。 Laravel將以相同的URL和JSON格式返回響應。

0

只需添加上你的要求有以下功能:

use Response; 
public function response(array $errors) 
{ 
     return Response::json($errors);  
}