【问题标题】:How to determine if a session with same variable is already there in laravel如何确定laravel中是否已经存在具有相同变量的会话
【发布时间】:2017-02-20 18:04:15
【问题描述】:

我正在使用 Laravel 框架。控制器中有一个函数可以创建名称为store_id的会话

StoreController.php

function initiate($id)
{
    //Some queries
    session['store_id' => 'some value'];
}

现在,如果我在一个选项卡上运行此功能,那么 session::get('store_id') 将会继续。但是如果我在同一个浏览器中打开另一个选项卡,然后再次运行意味着session('store_id') 将再次设置的功能。我该如何处理这种情况,如果已经有一个会话,那么它应该重定向到它的透视 url。

【问题讨论】:

    标签: php laravel session laravel-5 laravel-5.3


    【解决方案1】:

    好的,首先,Bruuuhhhh been there and done that

    好的,开始吧。如果已经有与store_id 的会话正在进行,那么您希望用户重定向或发回。

    在你的控制器中添加这个

    public function initiate()
    {
        if(session()->has('store_id'))
        {
            //What ever your logic
        }
        else
        {
            redirect()->to('/store')->withErrors(['check' => "You have session activated for here!."]);
        }
    }
    

    您很可能想知道用户可以在/store/other-urls 之后转到其他网址。是的,他可以。

    为了避免这种情况。添加自定义middleware

    php artisan make:middleware SessionOfStore //You can name it anything.
    

    在那个中间件中

    public function handle($request, Closure $next)
    {
        if($request->session()->has('store_id'))
        {
            return $next($request);
        }
        else
        {
            return redirect()->back()->withErrors(['privilege_check' => "You are not privileged to go there!."]);
        }
        return '/home';
    }
    

    在您的主商店页面中。添加anchor tag<a href="/stop">Stop Service</a>

    现在在您的web.php

    Route::group(['middleware' => 'SessionOfStore'], function()
    {
        //Add your routes here.
        Route::get('/stop', 'StoreController@flushSession');
    });
    

    现在您已限制对 url 的访问并检查了会话。

    现在

    public function flushSession()
    {
        //empty out the session and
        return redirect()->to('/home');
    }
    

    【讨论】:

      【解决方案2】:

      Laravel 会话助手有函数 has 来检查这个。

      if (session()->has('store_id'))
      {
          // Redirect to the store
      }
      else
      {
          // Set the store id
      }
      

      The documentation 包含可与会话助手一起使用的所有可能功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-27
        • 2011-05-18
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 2020-04-21
        • 2017-08-08
        相关资源
        最近更新 更多