【问题标题】:Laravel 5.4: controller method is called twice on a redirect to itLaravel 5.4:控制器方法在重定向到它时被调用两次
【发布时间】:2020-11-22 08:43:22
【问题描述】:

我遇到了一个问题,从一个路由重定向到另一个路由两次调用目标控制器方法。 This question 解决了类似的问题,但传递 301 状态代码的 OP 被认为是 accepted answer 中的问题,我没有指定任何状态代码。我也在使用会话状态作为参数。相关代码如下所示:

public function origin(Request $request) {
  // Assume I have set variables $user and $cvId
  return redirect()
    ->action('SampleController@confirmUser')
    ->with([
      'cvId' => $cvId,
      'userId' => $user->id,
     ]);
}

public function confirmUser(Request $request) {
  $cvId = session()->get('cvId');
  $userId = session()->get('userId');

  if (is_null($cvId) || is_null($userId)) {
    // This is reached on the second time this is called, as 
    // the session variables aren't set the second time
    return redirect('/home');
  }

  // We only see the view for fractions of a second before we are redirected home
  return view('sample.confirmUser', compact('user', 'cvId'));
}

任何想法可能导致这种情况?我没有任何next 中间件或控制器执行两次的相关问题中建议的任何其他可能原因。

感谢您的帮助!

【问题讨论】:

  • 对 Laravel 不是很熟悉,但是你有没有试过在方法中设置一个断点来查看第二次调用它的方法? (或者,或者,使用debug_print_backtrace()?)
  • @Jeto 感谢您的评论。翻看堆栈,只是一堆 Laravel 框架函数,没有来自我自己的代码。

标签: php laravel laravel-5 http-redirect laravel-controller


【解决方案1】:

您是否尝试过在参数中传递值?试试下面的代码。

public function origin(Request $request) {
  // Assume I have set variables $user and $cvId
  return redirect()->action(
    'SampleController@confirmUser', ['cvId' => $cvId, 'userId'=>$user->id]
);
}

public function confirmUser(Request $request) {
  $cvId = $request->cvId;
  $userId = $request->userId;

  if (is_null($cvId) || is_null($userId)) {
    // This is reached on the second time this is called, as 
    // the session variables aren't set the second time
    return redirect('/home');
  }

  // We only see the view for fractions of a second before we are redirected home
  return view('sample.confirmUser', compact('user', 'cvId'));
}

【讨论】:

  • 感谢您的回复!我想改用会话参数是有原因的,但是使用普通的请求参数似乎可以防止额外的重定向调用。任何想法为什么使用会话会导致这种情况?
  • 根据官方文档,重定向到Controller Actions。推荐参数。 laravel.com/docs/5.6/redirects#redirecting-controller-actions
猜你喜欢
  • 2017-12-12
  • 2014-02-06
  • 2017-09-20
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
相关资源
最近更新 更多