在laravel 5.1中请求验证失败后重定向到登录页面


Redirecting to the login page after fail request validation in laravel 5.1

我正在为移动应用程序创建Rest Full Api,我正在验证请求,它将我重定向到登录页面,但有错误。

这是我的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' => 'ApiController@createUser']);

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格式返回错误,但它也打印登录页面,我不明白为什么

如果您正在使用Postman测试API的,则无需覆盖请求类中的response()。可以按照以下步骤操作,

  1. 使自定义请求中authorize()中的return类型为true,

    public function authorize()
    {
       //make it true
       return true;
    }
    
  2. 转到邮差的标题部分,定义Accept类型,

    Accept:application/json
    
  3. 现在,点击API的端点,并点击。。对我来说很好。

这是通过覆盖app/Http/Requests/Request.php中的response方法完成的

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