简体   繁体   English

在 Laravel 中设置会话变量

[英]Set session variable in laravel

I would like to set a variable in the session using laravel this way我想以这种方式使用 laravel 在会话中设置一个变量

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谢谢

The correct syntax for this is:正确的语法是:

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

For Laravel 5.4 and later, the correct method to use is put :对于 Laravel 5.4 及更高版本,正确的使用方法是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.如果您需要设置一次,我会弄清楚您想要设置的确切时间并使用Events来完成。

For example, if you want to set it when someone logs in, you'd use:例如,如果您想在有人登录时设置它,您可以使用:

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

I think your question ultimately can be boiled down to this:我认为你的问题最终可以归结为:

Where can I set a long-lived value that is accessible globally in my application?我在哪里可以设置在我的应用程序中全局访问的长期值?

The obvious answer is that it depends.显而易见的答案是视情况而定。 What it depends on are a couple of factors:它取决于几个因素:

  • Will the value ever be different, or is it going to be the same for everybody?价值会有所不同,还是对每个人都一样?
  • How long exactly is long-lived?长寿究竟是多久? (Forever? A Day? One browsing 'session'?) (永远?一天?一次浏览“会话”?)

Config配置

If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config , eg app/config/companyname.php :如果每个人的值都相同并且很少更改,那么最好将它放在app/config下的配置文件中,例如app/config/companyname.php

<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')您可以通过Config::get('companyname.somevalue')从应用程序的任何位置访问此值

Session会议

If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session .如果您打算存储的值对于每个用户都不同,那么将它放在Session最合乎逻辑。 This is what you allude to in your question, but you are using incorrect syntax.这就是您在问题中提到的内容,但您使用的语法不正确。 The correct syntax to store a variable in Session is:在 Session 中存储变量的正确语法是:

Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:稍后检索它的正确语法是:

Session::get('somekey');

As far as when to perform these operations, that's a little up to you.至于何时执行这些操作,这取决于您。 I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:我可能会选择路由过滤器,如果在Laravel 4.x或中间件,如果使用Laravel 5.下面是使用路由过滤器,它利用另一个类实际拿出价值的例子:

// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point. 
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});

In Laravel 5.6, you will need to set it as:在 Laravel 5.6 中,您需要将其设置为:

session(['variableName' => $value]);

To retrieve it, is as simple as:要检索它,就像这样简单:

$variableName = session('variableName');

For example, To store data in the session, you will typically use the put method or the session helper:例如,要在会话中存储数据,您通常会使用put方法或session助手:

// Via a request instance...
$request->session()->put('key', 'value');

or要么

// Via the global helper...
session(['key' => 'value']);

for retrieving an item from the session, you can use get :要从会话中检索项目,您可以使用get

$value = $request->session()->get('key', 'default value');

or global session helper :或全局session助手:

$value = session('key', 'default value');

To determine if an item is present in the session, you may use the has method:要确定会话中是否存在项目,您可以使用has方法:

if ($request->session()->has('users')) {
//
}

in Laravel 5.4在 Laravel 5.4 中

use this method:使用这个方法:

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

To add to the above answers, ensure you define your function like this:要添加到上述答案,请确保像这样定义函数:

public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:注意“(Request $request)”,现在设置一个这样的会话:

$request->session()->put('key', 'value');

And retrieve the session in this way:并以这种方式检索会话:

$data = $request->session()->get('key');

To erase the session try this:要擦除会话试试这个:

$request->session()->forget('key');  

or要么

$request->session()->flush();

You can try你可以试试

 Session::put('variable_Name', "Your Data Save Successfully !");  
 Session::get('variable_Name');

In Laravel 6.x在 Laravel 6.x 中

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session https://laravel.com/docs/6.x/session

to set session you can try this:设置会话你可以试试这个:

$request->session()->put('key','value');

also to get session data you can try this:也可以尝试获取会话数据:

$request->session()->get('key');

If you want to get all session data:如果要获取所有会话数据:

$request->session()->all();

If you want persistence sessions,如果你想要持久性会话,

Method 1: use session()->save() or Session::save()方法一:使用session()->save()Session::save()

session(['key' => 'value']);
//or
session()->put('key', 'value');

//then
session()->save();

echo session('key');

Method 2: Move bellow line from protected $middlewareGroups of app\\Http\\Kernel.php to protected $middleware array as first line方法2:将波纹管线从protected $middlewareGroupsapp\\Http\\Kernel.phpprotected $middleware数组作为第一线

\Illuminate\Session\Middleware\StartSession::class,

Make sure the storage directory has write permission确保存储目录具有写权限

chmod -R a+rw storage/

Don't use dd() to verify session, use print_r()不要使用dd()来验证会话,使用print_r()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM