Laravel 5自定义验证重定向 [英] Laravel 5 custom validation redirection

查看:63
本文介绍了Laravel 5自定义验证重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,该网站由2个地方的2个不同的登录表单组成,一个位于导航栏上,另一个是登录页面,当系统捕获未记录的访问者时将使用该页面.

I have a website which consist of 2 different login form at 2 places, one on the navbar and the other one is a login page which will be used when the system catches an unlogged visitor.

我可以问我在LoginRequest.php中做错了什么吗?在其中,如果登录过程中存在任何类型的错误,我已经设置了一个条件以重定向到自定义登录页面?我的代码如下:

Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest 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 [
        'login_email'               =>  'required',
        'login_password'            =>  'required'
        ];
    }


    public function messages()
    {
        return [
            'login_email.required'          =>  'Email cannot be blank',
            'login_password.required'       =>  'Password cannot be blank'
        ];
    }

    public function redirect()
    {
        return redirect()->route('login');
    }
}

该代码假设如果在登录页面上有任何错误,但似乎没有重定向,则会重定向从导航栏登录的用户.

The code suppose to redirect users who login from the nav bar if there is any error to the login page but it doesn't seem to redirect.

谢谢.

推荐答案

找到了解决方案.我需要做的就是覆盖

Found a solutions. All I need to do is to override the initial response from

FormRequest.php

FormRequest.php

就像这样,它就像一种魅力.

like such and it works like a charm.

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever else

    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to('login')
         ->withInput($this->except($this->dontFlash))
         ->withErrors($errors, $this->errorBag);
}

这篇关于Laravel 5自定义验证重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆