为所有请求创建中间件并在laravel中设置会话变量

时间:2017-02-15 10:56:03

标签: laravel

我正在尝试在中间件中设置会话变量,我正在尝试为所有请求配置。我似乎无法让它发挥作用。错误是 Request.php第905行中的RuntimeException: 会话存储未按要求设置。

也许我在kernel.php中注册中间件时犯了错误?

我的中间件代码     

namespace App\Http\Middleware;

use Closure;
use App\shoppingChart;

class sessionChecker
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

       if(!$request->session()->has('test')){
           $request->session()->put('test','baran');
       }

       return $next($request);
    }
}

我的kernel.php是

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\sessionChecker::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

1 个答案:

答案 0 :(得分:0)

    当请求通过angular.module(MY_APP).component('bmwCarInfo', { bindings: { days: '<' }, template: ` <span> <strong>{{$ctrl.days}}-Day Evaluation Period</strong> <br />Charges will be applied once evaluation period finishes! </span> ` }); <div ng-controller="CarController as $ctrl" ng-cloak> <bmw-car-info days="$ctrl.days" /> </div> 时,
  • \Illuminate\Session\Store被设置为Request
  • 全局中间件堆栈网络中间件堆栈之前运行。因此\Illuminate\Session\Middleware\StartSession未设置为\Illuminate\Session\Store

在这种情况下有两种解决方案。根据您希望应用程序执行的目的。

  • 用作GlobalMiddleWare。 (所有请求都将得到处理)

    1. Request实例放入中间件构造函数中。然后,您可以访问会话存储。有关详细信息:请参见Offical Docs

    2. 请注意,\Illuminate\Session\Store中间件可以从您在StartSession中配置的驱动程序会话处理程序进行初始化或重新初始化。

这里我展示了如何使用注入的config/session.php实例将当前请求的IP地址放入会话 using dependency injection

  • 使用 web 中间件(仅处理Web路由。不适用于:Console,API .... etc)

    1. Store类中,在Kernel数组中。将中间件类名放在$middlewareGroups之后。然后,您将可以在中间件类中调用\Illuminate\Session\Middleware\StartSession

这是我定义Web中间件的方式

defining call order

我编辑的中间件类将是这样

enter image description here