【问题标题】:Laravel Form Request not being passed to argumentLaravel 表单请求未传递给参数
【发布时间】:2015-11-18 16:27:18
【问题描述】:

我正忙于将应用程序从 Laravel 4.2 迁移到 5.1,并且遇到了表单请求问题。这可能是我缺少的一些简单的东西 - 不太确定。

如果SignInRequest 成功授权请求,则以下方法旨在尝试登录。但是,如果验证通过,SignInRequest 不会传递给 attemptSignIn,这会抛出该过程并出现以下错误:

传递给 App\Http\Controllers\Auth\AuthController::attemptSignIn() 的参数 2 必须是 App\Http\Requests\SignInRequest 的实例,没有给出

这是有问题的方法(控制器是AuthController),它尝试使用用户名或电子邮件地址登录:

public function attemptSignIn($type = 'regular', SignInRequest $request)
{
    switch ($type) {
        case 'regular':
            $identifierFieldName = 'account_identifier';
            $field = filter_var($request->input($identifierFieldName), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
            $request->merge([$field => $request->input($identifierFieldName)]);
            $specifics = $request->only($field, 'passphrase');
            $specifics['activated'] = (int) true;
            if ($this->auth->attempt($specifics)) {
                return redirect()->intended($this->redirectPath);
            } else {
                return redirect($this->signInPath)
                    ->with('authError', "The credentials you've provided are incorrect.")
                    ->with('authErrorType', 'warning')
                    ->withInput($request->only($identifierFieldName))
                    ->withErrors();
            }
            break;

        case 'oota':

            break;

        default:
            return redirect($this->signInPath);
            break;
    }
}

表单请求很简单,指定rulesmessagesauthorize (return true)。

但是,如果验证失败,SignInRequest 将传递给该方法,并相应地显示错误。

我错过了什么吗?

【问题讨论】:

  • 您是否在控制器中注入了SignInRequest
  • attemptSignIn 是一种控制器方法。你是说我还需要将它注入到构造函数中?
  • 传递给方法的第二个参数SignInRequest 必须在构造函数中注入或int
  • 那么,我应该将$this->request 分配给构造函数中的表单请求吗?如果是这样,我将无法在attemptSignIn 中使用withErrors(),除非错误自动传递给视图...
  • 你不需要传递错误,它们是默认传递的。 https://laracasts.com/series/whats-new-in-laravel-5/episodes/3看视频,很有帮助。

标签: php validation laravel authentication request


【解决方案1】:
use \path\to\your\ClassRequest as MyRequest

protected $myrequest;

public function __construct(\path\to\your\ClassRequest $request){
   $this -> myrequest = $request; // use directly in your method or any method
}

希望对您有所帮助。

public function post_form(MyRequest $request) {
  your code here

}

【讨论】:

  • 不幸的是,没有。如果我使用第一种方法,我会得到异常。如果我将它注入构造函数并分配给$this->request,我会在/signin/dashboard 之间得到一个重定向循环。
  • 抱歉,这是一个较早的重定向循环。 /signin 不断重定向到它自己,但没有指示它这样做。我可能会在这个上切换回手动验证。
  • 啊,你是对的——看来参数顺序是问题所在。它现在似乎正在工作,只是它没有使用有效凭据进行身份验证。会单独解决的。感谢您的帮助,非常感谢。
猜你喜欢
  • 2016-04-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2016-01-17
  • 2012-01-13
  • 1970-01-01
相关资源
最近更新 更多