Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

php - Set session variable in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct syntax for this is:

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

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

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

To get the variable, you would 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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...