Laravel 5自定义验证重定向

Ken*_*Yap 9 php laravel laravel-routing laravel-5 laravel-validation

我有一个网站,包括2个不同的登录表单,2个位置,一个在导航栏上,另一个是登录页面,将在系统捕获未登记的访问者时使用.

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

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ken*_*Yap 7

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

FormRequest.php

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

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您想重定向到特定的网址,请使用 protected $redirect

class LoginRequest extends Request
{
    protected $redirect = "/login#form1";

    // ...
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想重定向到命名路由,请使用 $redirectRoute

class LoginRequest extends Request
{
    protected $redirectRoute = "session.login";

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • “缺少 [路线:restaurant-update-images.user] [URI:panel/restaurant/update-images/{user}] 所需的参数。” 在 Laravel 5.7 中为什么? (2认同)

小智 5

如果您不想在请求上使用 validate 方法,您可以使用 Validator Facade 手动创建一个验证器实例。Facade 上的 make 方法生成一个新的验证器实例:参考Laravel 验证

 public function store(Request $request)
   {
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
    }
Run Code Online (Sandbox Code Playgroud)


yma*_*kux 5

这在 Lara 7 中有效添加一个锚点,以便在验证失败时跳转到评论表单

protected function getRedirectUrl()
{
    return parent::getRedirectUrl() . '#comment-form';
}
Run Code Online (Sandbox Code Playgroud)