`Auth::user()` 在 Laravel 中为什么是 null?

huangapple go评论117阅读模式
英文:

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',
],

huangapple
  • 本文由 发表于 2023年3月7日 15:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定