【问题标题】:Laravel, why using Auth::id() in route file (web.php) returns null?Laravel,为什么在路由文件(web.php)中使用 Auth::id() 返回 null?
【发布时间】:2019-12-06 09:55:58
【问题描述】:

我只是安装了新的 laravel 应用程序,然后我继续通过 php artisan make:auth 进行身份验证

问题是dump(Auth::id()) 在路由文件(web.php)中返回null,即使我已经登录了。

如果

Route::get('test', function() { 
    dump(Auth::id()); }
);

它返回当前登录的用户ID。

因为我想根据路由文件 (web.php) 中的登录用户 ID 进行查询。

例如(web.php)

$test = DB::table('tests')->where('user_id', Auth::id())->get();
dump($test) // returns empty because Auth::id() returns null

更新

【问题讨论】:

  • 您应该使用中间件按 ID 或角色路由登录用户
  • 不检查路由中的登录用户。如果您需要检查用户是否已登录,请使用中间件。
  • 任何想法如何做到这一点?
  • 应该是Auth::user()->id
  • 您并没有真正在web.php 中进行查询。你到底想达到什么目的?

标签: php laravel


【解决方案1】:

阅读 laravel 文档:https://laravel.com/docs/5.8/authentication

如果你想在没有 auth 中间件的情况下获取用户 ID,试试这个

对于默认守卫,

if ( auth()->check() )
    return auth()->id();

对于特定的守卫,

if ( auth()->guard('guard-name')->check() )
    return auth()->guard('guard-name')->id();

【讨论】:

  • 问题是,无论我登录与否,auth()->check 总是返回 false
  • 如果您使用默认守卫auth()->check() 登录将返回true。使用check() 而不是check
  • 无论我是否登录,它仍然返回false。看看我更新的问题
  • 将代码放在控制器或路由回调函数中,而不是在路由门面之外。 Route::get('test', function () { dump(auth()->check()); }); 如果您已登录,将返回 true
  • 但问题是,我需要在输入 url 之前进行查询,就像我在问题中提供的示例一样
猜你喜欢
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2019-10-26
  • 2018-12-22
  • 2017-07-21
  • 1970-01-01
相关资源
最近更新 更多