问题
i'm using laravel 6 and have 2 route in my app; index and dashboard.
My routes/web
is:
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController@index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});
i added dashboard route recently.
Auth::user()
is null when i dump it in dashboard route but doesn't in index. What's the
回答1:
Your Controller is instantiated before the middleware stack has ran; this is how Laravel can know what middleware you have set via the constructor. Because of this you will not have access to the authenticated user or sessions at this point. Ex:
public function __construct()
{
$this->user = Auth::user(); // will always be null
}
If you need to assign such a variable or access this type of information you would need to use a controller middleware which will run in the stack after the StartSession
middleware:
public function __construct()
{
$this->middleware(function ($request, $next) {
// this is getting executed later after the other middleware has ran
$this->user = Auth::user();
return $next($request);
});
}
When the dashboard
method is called, the middleware stack has already passed the Request all the way through to the end of the stack so all the middleware needed for Auth
to be functioning and available has already ran at that point which is why you have access to Auth::user()
there.
回答2:
I think that this has something to do with the 'web' middleware. If you take a look into the Kernel.php (In app\Http) you will find the web middleware group.
This will show you that it actually calls a middleware called StartSession. Based on your route file (where web is not included as a middleware) I would think that you don't have a session in your Controller and there for no access to it.
I don't quite understand why this only happens in your /dashboard route, because the issue should also be in your /index route (unless you added the web middleware somewhere in your TodoController).
I think that this should do the trick:
Route::middleware(['web', 'auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController@index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});
回答3:
If you fire php artisan make:auth
command.
It's doesn't matter where you define because of it's only define auth route
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController@index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});
Auth::routes();
来源:https://stackoverflow.com/questions/58660711/authuser-is-null-in-new-route