2015-12-03 60 views
1

我正在爲移動應用程序創建Rest Full Api,我正在驗證請求,它將我重定向到出現錯誤的登錄頁面。laravel 5.1中失敗請求驗證後重定向到登錄頁面

這是我ApiController(我對所有API創建的):

use App\User as UserModel; 
use App\Fb_friend as FbFriendsModel; 
use App\Http\Requests\UserRequest; 

class ApiController extends Controller 
{ 

    /** 
    * Create a new movie model instance. 
    * 
    * @return void 
    */ 
    public function __construct(UserModel $user, FbFriendsModel $fb_friends){ 
     $this->user = $user; 
     $this->fb_friends = $fb_friends; 
    } 
    public function createUser (UserRequest $request) { 
     // some code here 
    } 

路線:

Route::post('createUser', ['as' => 'createUser', 'uses' => '[email protected]']); 

UserRequest.php:

public function rules() 
    { 
     return [ 
      'fb_id' => 'required|unique:users', 
      'username' => 'required|unique:users', 
      'email' => 'required|unique:users', 
      'image' => 'required', 
      'device_id' => 'required', 
      'status' => 'required', 
     ]; 
    } 

我有重載函數Request.php錯誤格式:

abstract class Request extends FormRequest 
{ 
    protected function formatErrors(Validator $validator) 
    { 
     return [$validator->messages()->toJson()]; 
    } 
} 

當我嘗試調用通過郵遞員服務,它返回我的錯誤JSON格式,但它也打印登錄頁面,我不是得到原因?

回答

0

已被覆蓋的response方法app/Http/Requests/Request.php

public function response(array $errors) { 
     if ($this->ajax() || $this->wantsJson() || Request::isJson()) { 
      $newError = []; 
      $newError['result'] = false; 
      $newError['errors'] = $errors; 
      // in the above three lines I have customize my errors array. 

      return new JsonResponse($newError, 422); 
     } 

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

完畢後,我們還需要使用JsonResponse類頂部

use Illuminate\Http\JsonResponse; 

來源:https://laracasts.com/discuss/channels/general-discussion/laravel-5-validation-formrequest

相關問題