英文:
why Auth::user() is null in laravel?
问题
我创建了一个像这样的web.php路由:
Route::group(['middleware' => ['web', 'auth']], function () {
Route::namespace('App\Http\Controllers\Admin')->prefix('dashboard')->group(function () {
Route::get('/index', 'DashboardController@index')->name('dashboard.index');
});
});
但在DashboardController > index()
中,Auth::user()
返回null。
class DashboardController extends Controller
{
public function index(){
dd(Auth::user());
return view('panel.admin.dashboard');
}
}
在LoginController > login()
中,在Auth::attempt($credentials)
之后,Auth::user()
是正确的。
class LoginController extends Controller
{
public function login (AdminLoginRequest $request)
{
$credentials = $request->only('phone', 'password');
if (Auth::attempt($credentials))
{
return redirect()->route('dashboard.index') ;
}
return redirect()->back()->withErrors(['msg' => '无效的输入']);
}
}
根据我的理解,最常见的错误是从控制器中检索用户和缺少web中间件。我会考虑这些。
缺少什么?
提前感谢。
英文:
I've created a web.php route like this :
Route::group(['middleware' => ['web' , 'auth']], function () {
Route::namespace('App\Http\Controllers\Admin')->prefix('dashboard')->group(function () {
Route::get('/index', 'DashboardController@index')->name('dashboard.index');
});
});
but in the DashboardController > index()
Auth::user()
return null.
class DashboardController extends Controller
{
public function index(){
dd(Auth::user());
return view('panel.admin.dashboard');
}
}
in the LoginController > login()
after Auth::attempt($credentials)
the Auth::user()
is correct.
class LoginController extends Controller
{
public function login (AdminLoginRequest $request)
{
$credentials = $request->only('phone', 'password');
if (Auth::attempt($credentials))
{
return redirect()->route('dashboard.index') ;
}
return redirect()->back()->withErrors(['msg' => 'invalid inputs']);
}
}
As I understand, most commonly mistakes are retrieving user from controller and absence of web middleware. And I'am consider it.
what is missing ?
thanks in advance
答案1
得分: 1
对我来说:我不得不进入我的config/auth.php文件,并将'guard' => 'web'进行设置。(之前是'web')
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
英文:
For me: I had to fix this by going into my config/auth.php and set the 'guard' => 'web'. (it was web before)
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论