在Laravel中设置会话变量 [英] Set session variable in laravel

查看:97
本文介绍了在Laravel中设置会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过laravel在会话中设置一个变量

I would like to set a variable in the session using laravel this way

Session::set('variableName')=$value;

但是问题是我不知道将这段代码放在哪里,因为我想设置一次(当访客访问主页或其他页面时)? 我的主要想法是使用全局变量在所有应用程序控制器中使用它,我听说过一些与配置变量有关的信息,但是我不确定使用配置变量还是仅使用会话是个好主意? 谢谢

but the problem is that I don't know where to put this code, 'cause I would like to set it for one time (when the guest visite the home page or any other page)? The main idea is to use a global variable to use it in all application controllers, I heared about something related to configuration variables but I'm not sure if it will be a good Idea to use config variables or only the session? Thanks

推荐答案

正确的语法是...

Session::set('variableName', $value);

对于Laravel 5.4和更高版本,正确使用的方法是put.

For Laravel 5.4 and later, the correct method to use is put.

Session::put('variableName', $value);

要获取变量,请使用...

To get the variable, you'd use...

Session::get('variableName');

如果您需要设置一次,我会弄清楚您到底是什么时候设置它,然后使用事件"来进行设置.例如,如果要在某人登录时进行设置,则可以使用...

If you need to set it once, I'd figure out when exactly you want it set and use Events to do it. For example, if you want to set it when someone logs in, you'd use...

Event::listen('auth.login', function()
{
    Session::set('variableName', $value);
});

这篇关于在Laravel中设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆