php Laravel - 未按要求设置会话存储
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34449770/
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
Laravel - Session store not set on request
提问by mattrick
I recently created a new Laravel project and was following along the guide on Authentication. When I visit either my login or register route, I get the following error:
我最近创建了一个新的 Laravel 项目,并按照身份验证指南进行操作。当我访问我的登录或注册路由时,我收到以下错误:
ErrorException in Request.php line 775:
Session store not set on request. (View: C:\Users\Matthew\Documents\test\resources\views\auth\register.blade.php)
I haven't edited any core Laravel files, I've only created the views and added the routes to my routes.php file
我没有编辑任何核心 Laravel 文件,我只创建了视图并将路由添加到我的 routes.php 文件中
// Authentication routes
Route::get('auth/login', ['uses' => 'Auth\AuthController@getLogin', 'as' => 'login']);
Route::post('auth/login', ['uses' => 'Auth\AuthController@postLogin', 'as' => 'login']);
Route::get('auth/logout', ['uses' => 'Auth\AuthController@getLogout', 'as' => 'logout']);
// Registration routes
Route::get('auth/register', ['uses' => 'Auth\AuthController@getRegister', 'as' => 'register']);
Route::post('auth/register', ['uses' => 'Auth\AuthController@postRegister', 'as' => 'login']);
I don't have much experience with Laravel, so please excuse my ignorance. I'm aware that there is another questionasking this same thing, but neither of the answers seem to work for me. Thanks for reading!
我对 Laravel 没有太多经验,所以请原谅我的无知。我知道还有另一个问题在问同样的事情,但两个答案似乎都不适合我。谢谢阅读!
Edit:
编辑:
Here's my register.blade.php as requested.
这是我要求的 register.blade.php。
@extends('partials.main')
@section('title', 'Test | Register')
@section('content')
<form method="POST" action="/auth/register">
{!! csrf_field() !!}
<div class="ui input">
<input type="text" name="name" value="{{ old('name') }}" placeholder="Username">
</div>
<div class="ui input">
<input type="email" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
<div class="ui input">
<input type="password" name="password" placeholder="Password">
</div>
<div class="ui input">
<input type="password" name="password_confirmation"placeholder="Confirm Password">
</div>
<div>
<button class="ui primary button" type="submit">Register</button>
</div>
</form>
@endsection
回答by Cas Bloem
You'll need to use the web middlewareif you need session state, CSRF protection, and more.
如果您需要会话状态、CSRF 保护等,则需要使用Web 中间件。
Route::group(['middleware' => ['web']], function () {
// your routes here
});
回答by Waiyl Karim
If adding your routes
inside the web middleware
doesn't work for any reason then try adding this to $middleware
into Kernel.php
如果添加您的routes
insideweb middleware
因任何原因不起作用,请尝试将其添加$middleware
到Kernel.php
protected $middleware = [
//...
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
回答by George Kagan
In my case (using Laravel 5.3) adding only the following 2 middleware allowed me to access session data in my API routes:
在我的情况下(使用 Laravel 5.3)只添加以下 2 个中间件允许我访问 API 路由中的会话数据:
\App\Http\Middleware\EncryptCookies::class
\Illuminate\Session\Middleware\StartSession::class
\App\Http\Middleware\EncryptCookies::class
\Illuminate\Session\Middleware\StartSession::class
Whole declaration ($middlewareGroups
in Kernel.php):
整个声明($middlewareGroups
在 Kernel.php 中):
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
回答by u1581544
If Cas Bloem's answer does not apply (i.e. you've definitely got the web
middleware on the applicable route), you might want to check the order of middlewares in your HTTP Kernel.
如果 Cas Bloem 的回答不适用(即您肯定web
在适用的路由上安装了中间件),您可能需要检查 HTTP 内核中中间件的顺序。
The default order in Kernel.php
is this:
默认顺序Kernel.php
是这样的:
$middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
];
Note that VerifyCsrfToken
comes after StartSession
. If you've got these in a different order, the dependency between them can also lead to the Session store not set on request.
exception.
请注意,VerifyCsrfToken
在StartSession
. 如果您以不同的顺序获得这些,它们之间的依赖关系也会导致Session store not set on request.
异常。
回答by Daan
A problem can be that you try to access you session inside of your controller's __constructor()
function.
一个问题可能是您尝试访问控制器__constructor()
函数内的会话 。
From Laravel 5.3+ this is not possible anymore because it is not intended to work anyway, as stated in the upgrade guide.
从 Laravel 5.3+ 开始,这不再可能,因为它无论如何都不打算工作,如升级指南中所述。
In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
在以前版本的 Laravel 中,您可以在控制器的构造函数中访问会话变量或经过身份验证的用户。这从未打算成为框架的显式特征。在 Laravel 5.3 中,您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。
For more background information also read Taylorhis response.
有关更多背景信息,请阅读Taylor他的回复。
Workaround
解决方法
If you still want to use this, you can dynamically create a middleware and run it in the constructor, as described in the upgrade guide:
如果你还想使用这个,你可以动态创建一个中间件并在构造函数中运行它,如升级指南中所述:
As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class ProjectController extends Controller { /** * All of the current user's projects. */ protected $projects; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware(function ($request, $next) { $this->projects = Auth::user()->projects; return $next($request); }); } }
作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序运行的是 Laravel 5.3.4 或更高版本:
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class ProjectController extends Controller { /** * All of the current user's projects. */ protected $projects; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware(function ($request, $next) { $this->projects = Auth::user()->projects; return $next($request); }); } }
回答by izzaki
Laravel [5.4]
Laravel [5.4]
My solution was to use global session helper: session()
我的解决方案是使用全局会话助手: session()
Its functionality is a little bit harder than $request->session().
它的功能比$request->session()稍微难一些。
writing:
写作:
session(['key'=>'value']);
pushing:
推:
session()->push('key', $notification);
retrieving:
检索:
session('key');
回答by u1357988
In my case I added the following 4 lines to $middlewareGroups (in app/Http/Kernel.php):
就我而言,我将以下 4 行添加到 $middlewareGroups(在 app/Http/Kernel.php 中):
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
'throttle:60,1',
'bindings',
],
IMPORTANT: The 4 new lines must be added BEFORE 'throttle' and 'bindings'!
重要提示:必须在 'throttle' 和 'bindings' 之前添加 4 个新行!
Otherwise a "CSRF token not match" error will rise. I've struggled in this for several hours just to find the order is important.
否则会出现“CSRF 令牌不匹配”错误。我已经在这方面挣扎了几个小时,只是为了发现订单很重要。
This allowed me to access session in my API. I also added VerifyCsrfToken as when cookies/sessions are involved, CSRF needs to be taken care of.
这允许我在我的 API 中访问会话。我还添加了 VerifyCsrfToken,因为当涉及 cookie/sessions 时,需要处理 CSRF。
回答by Henrique Duarte
Do you can use ->stateless()
before the ->redirect()
.
Then you dont need the session anymore.
你可以->stateless()
在->redirect()
. 然后你不再需要会话了。
回答by gtamborero
It's not on the laravel documentation, I have been an hour to achieve this:
它不在laravel文档中,我花了一个小时来实现这一目标:
My session didn't persist until i used the "save" method...
我的会话没有持续,直到我使用“保存”方法......
$request->session()->put('lang','en_EN');
$request->session()->save();
回答by Learner
Laravel 5.3+ web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.
Laravel 5.3+ web 中间件组由 RouteServiceProvider 自动应用到你的 routes/web.php 文件。
Unless you modify kernel $middlewareGroups array in an unsupported order, probably you are trying to inject requests as a regular dependency from the constructor.
除非您以不受支持的顺序修改内核 $middlewareGroups 数组,否则您可能正在尝试将请求作为构造函数的常规依赖项注入。
Use request as
使用请求作为
public function show(Request $request){
}
instead of
代替
public function __construct(Request $request){
}