Laravel-扩展Illuminate\Http\Request并使用会话



我已经扩展了IlluminateHttpRequest类,并将其传递给我的控制器。

use IlluminateHttpRequest;
class MyRequest extends Request
{
...
}

控制器

class MyController
{
// Doesnt work
public function something(MyRequest $request) {
var_dump($request->session())
}
// Does work
public function something(IlluminateHttpRequest $request) {
var_dump($request->session())
}
}

所以当我尝试获取会话$request->session()时,我会获得RuntimeException - Session store not set on request.

我觉得这与不按我的自定义请求运行中间件有关,但我不知道如何让它发挥作用。帮助或指向正确的方向将是非常值得的。

提供更多信息。我正在努力制作一个巫师。多个页面,其中一个页面的内容取决于前几页上的选择。我将数据存储在会话中,在最后一页上;"东西";并清除当前用户的会话存储。

因为它有很多行代码,而且会话安装是根据请求进行的,所以我认为将所有这些行隐藏在自定义请求中是很好的,而在控制器中只需调用$myRequest->storeInputs()

在我看来,这就是";最优雅的";在这种特殊的情况下,所以我更愿意以这种方式完成它,但如果有更好的方法,我也愿意接受不同的解决方案。

总结:基本上,我应该把存储和检索sesison数据的所有行隐藏在哪里?

解决方案:事实上,我通过扩展FormRequest解决了这个问题,因为它是最适合我尝试做的事情的解决方案。然而,我接受了提供的答案,因为我相信它通常是更好的解决方案,如果不是在这个非常特殊的情况下,我会使用它。

经典的Laravel请求已经得到了一堆您在自定义请求中没有捕捉到的设置。为了实现这一点,您应该设置一个中间件(在您的用例中可能是全局的(,用您的中间件替换Laravel容器中的旧请求。

<?php
namespace AppHttpMiddleware;
use AppHttpMyRequest;
use Closure;
use IlluminateContractsFoundationApplication;
use IlluminateHttpRequest;
class CustomizeRequest
{
/**
* @var IlluminateContractsFoundationApplication
*/
protected $app;
/**
* @var AppHttpMyRequest
*/
protected $myRequest;
/**
* @param  IlluminateContractsFoundationApplication  $app
* @param  AppHttpMyRequest  $myRequest
*/
public function __construct(Application $app, MyRequest $myRequest)
{
$this->app = $app;
$this->myRequest = $myRequest;
}
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $request
* @param  Closure  $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$this->app->instance(
'request', Request::createFrom($request, $this->myRequest)
);
return $next($this->myRequest);
}
}

最新更新