2017-02-20 55 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包含可用於會話幫助程序的所有可能功能。

相關問題