如何在 Laravel 中为整个应用程序设置全局会话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37907277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:01:25  来源:igfitidea点击:

How to set a global session for the whole app in Laravel?

laravelsessionglobal

提问by Okay

How can I set a global session in Laravel. In a normal PHP-script a global session like $_SESSION['myvar']dies if the browser is closed or the function session_destroy()/unset()is called.

如何在 Laravel 中设置全局会话。在普通的 PHP 脚本中,$_SESSION['myvar']如果浏览器关闭或函数session_destroy()/unset()被调用,则全局会话将终止。

I tried this in Laravel, but it does not work in a controller extends BaseController:

我在 Laravel 中尝试过这个,但它在控制器扩展 BaseController 中不起作用:

Session::set( 'id', $user->id );
Session::get( 'id' );

The Context of my code is:

我的代码的上下文是:

// ROUTES
Route::get( '/', 'MyController@setSession' );


// CONTROLLER
class MyController extends Controller
{
    public function setSession( )
    {
       // ...
    Session::set( 'id', $user->id );
    return view('access');  
    }
}


// VIEW -> LOST Session
@if (Session::has('id') && Session::get('id') == 'hsdiwe78912hj')
    I have access!
@else
    I must stay here! <!-- I always get this -->
@endif 

回答by MD. ABU TALHA

use

Session::put('id', $user->id );
Session::get('id' );
Session::forget('id' );

回答by Okay

Thank you for your hints! I did not know, that Laravel does not use normal $_SESSION or session_start as like PHP uses.

谢谢你的提示!我不知道,Laravel 不像 PHP 那样使用普通的 $_SESSION 或 session_start。

The hint of yesterday: config/session.php has to be edited:

昨天的提示: config/session.php 必须编辑:

'expire_on_close' => true,  // expires when browser is closed

回答by Qevo

It seems that you are not properly defining $user->id. Try this:

看来您没有正确定义$user->id. 尝试这个:

Session::set( 'id', Auth::id() );