【问题标题】:laravel , getting Auth::user() table namelaravel ,获取 Auth::user() 表名
【发布时间】:2015-10-03 18:00:38
【问题描述】:

laravel 版本:5.0

我目前正在 laravel 中制作管理员登录中间件。

我使用 laravel 默认身份验证开箱即用。 在这种状态下,我已经成功登录了。

据我所知,我可以通过 Auth::User()->id; 获取用户 ID, 但问题是:我找不到检索表名的方法;

下面是我执行dd(Auth::User());的结果

如您所见,它包含信息 #table:"admins"

Admin {#177 ▼
  #table: "admins"
  #fillable: array:3 [▶]
  #hidden: array:2 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:7 [▶]
  #original: array:7 [▶]
  #relations: []
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dates: []
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
}

这是我要检查表名是否为管理员的中间件:

<?php namespace App\Http\Middleware;
use Closure;
use Auth;

class AdminMiddleware extends Model{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if(Auth::User()->getTable() == 'admins') //this doesnt work
        {
            return $next($request);
        }
        else
        {
            return response('Unauthorized.', 401);
        }

    }

}

我试图从 laravel 文档中寻找它并在 stackoverflow 中搜索,似乎我什么都没有。

问:我需要从 Auth:: 调用什么方法来获取表名?

如果有更好的做法,请不要犹豫。

【问题讨论】:

  • 为什么要取表名?
  • 我有用户表和管理员表,我试图验证登录凭据是否是管理员,我错过了什么..?这种方法看起来很脏

标签: php authentication laravel-5


【解决方案1】:

如果您的管理员class 正在扩展Eloquent\ModelAdmin::getTable()$adminInstance-&gt;getTable() 应该可以工作。

【讨论】:

  • 感谢您的回复。对不起,我已经改进了我的问题以获取更多详细信息……您是说我的 AdminMiddleware 课程吗?导致我试图从当前经过身份验证的用户获取表名,而不是从我的数据库中获取
【解决方案2】:

不要为管理员和用户创建两个单独的表,而是将他们的凭据放入同一个表中,并使用第二个表,即角色,其中将包含用户角色的详细信息。如果您想要相同的表结构和代码,请告诉我,我会分享它

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2020-10-03
    • 2015-05-13
    • 2018-11-15
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多