【问题标题】:Change redirection after validation failed - laravel验证失败后更改重定向 - laravel
【发布时间】:2016-05-11 12:51:24
【问题描述】:

我正在验证用户注册表

对于 EX:(Requests validation class)

class UserCreateAccountRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'email' => 'required|unique:users,email',
            'password' => 'required|min:6|max:32'
        ];
    }

}

如果电子邮件已经注册我想重定向到密码重置页面。

如何在不将验证放入控制器的情况下使用请求验证类来实现这一点?

【问题讨论】:

    标签: validation laravel-5.1


    【解决方案1】:

    在授权函数里面检查邮件是否已经存在,

    public function authorize()
    {
        $email = Request::input('email');
    
        $result = User::where('email',$email)
                ->exists();
    
        if($result)
        {
            return false;
        }
        return true;
    }
    

    如果返回 false,forbiddenResponse 函数将被触发,因此您需要包含该函数,并且在其中您可以重定向到您想要的页面。如果电子邮件已经存在,此函数只会返回 false。

     public function forbiddenResponse()
    {
        return redirect('password_reset');
    }
    

    就是这样。下面是Request类的结构供大家参考,

    <?php namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    use Response;
    
    class FriendFormRequest extends FormRequest
    {
    
    public function rules()
    {
        return [
            'first_name' => 'required',
            'email_address' => 'required|email'
        ];
    }
    
    public function authorize()
    {
        // Only allow logged in users
        // return \Auth::check();
        // Allows all users in
        return true;
    }
    
    // OPTIONAL OVERRIDE
    public function forbiddenResponse()
    {
        // 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
        return Response::make('Permission denied foo!', 403);
    }
    
    // OPTIONAL OVERRIDE
    public function response()
    {
        // If you want to customize what happens on a failed validation,
        // override this method.
        // See what it does natively here: 
        // https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Http/FormRequest.php
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2018-06-13
      • 2016-01-23
      • 2016-01-12
      相关资源
      最近更新 更多