2017-02-20 52 views
0

我正在使用Laravel框架。有一个在控制器中的功能与名称store_id如何确定具有相同变量的会话是否已经存在laravel

StoreController.php

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

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

回答

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', '[email protected]'); 
}); 

现在你必须限制访问的URL,并检查了会议。

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

现在

1

Laravel会话帮手具有功能has来检查这一点。

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

The documentation包含可用于会话帮助程序的所有可能功能。

相关问题