如何确定laravel中是否已存在具有相同变量的会话

时间:2017-02-20 18:04:16

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

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

的会话

StoreController.php

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

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

2 个答案:

答案 0 :(得分:1)

Laravel会话助手具有函数has来检查它。

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

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

答案 1 :(得分: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');
});

现在您已限制访问网址并检查了会话。

现在在

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