如何在自定义类 Laravel 5 中使用会话?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43048945/
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
How to use session in custom class laravel 5?
提问by Reynald Henryleo
here is my code:
这是我的代码:
<?php
use Illuminate\Support\Facades\Session;
namespace App\CustomLibrary
{
class myFunctions {
public function is_login() {
if(Session::get('id') != null){
return TRUE;
}
}
}
}
?>
I'm new in laravel 5, i just added a new custom function. And inside that function i wanna check a session ('id)? But i've got an error like this
我是 Laravel 5 的新手,我刚刚添加了一个新的自定义函数。在那个函数里面我想检查一个会话('id)?但我有这样的错误
FatalErrorException in myFunctions.php line 8: Class 'App\CustomLibrary\Session' not found
在 myFunctions.php 第 8 行中出现 FatalErrorException:找不到类“App\CustomLibrary\Session”
I need to know how to use session properly.
我需要知道如何正确使用会话。
回答by Alexey Mezenin
Add this clause to the top of the class, right after namespace
part:
将此子句添加到类的顶部,紧跟在namespace
部分之后:
use Session;
Or use full namespace:
或者使用完整的命名空间:
if (\Session::get('id') != null)
Or use the session()
helper:
或者使用session()
助手:
if (session('id') != null)
回答by apokryfos
Your use
needs to be afterthe namespace declaration:
你use
需要为之后的命名空间声明:
//use Illuminate\Support\Facades\Session; //Not here
namespace App\CustomLibrary
use Illuminate\Support\Facades\Session; //Here
Anything that is use
d before the namespace is used within the global namespace which changes once a namespace is declared.
use
命名空间之前的任何d 都在全局命名空间中使用,一旦声明命名空间就会改变。
回答by Gowthaman D
use Session;in Model and Controller
使用会话;在模型和控制器中
// Via a request instance...
// 通过请求实例...
$request->session()->put('key', 'value');
$request->session()->put('key', 'value');
// Via the global helper...
// 通过全局助手...
session(['key' => 'value']);
session(['key' => 'value']);
for more details https://laravel.com/docs/5.1/session