【问题标题】:laravel Auth::check not working in Modellaravel Auth::check 在模型中不起作用
【发布时间】:2017-05-12 04:35:21
【问题描述】:

我有一个 API,可以使用或不使用身份验证访问某些路由。

用户可以打开药房,如果他登录了,他可能喜欢或不喜欢;如果他没有登录,则为0。

这是我的模型:

protected $fillable = ['name', 'city_id', 'block_id', 'address', 'contact', 'image', 'status', 'user_id'];

protected $appends = ['favourite'];

public function getFavouriteAttribute()
{
    //return \auth()->id();
    if (\auth()->check()) {
        return (FavouritePharmacy::where('user_id', \auth()->id())->where('pharmacy_id', $this->id)->count() == 1) ? 1 : 0;
    }
    return 0;
}
}

问题是favourite属性总是返回0。

当我检查身份验证时,它返回null

我该如何解决这个问题?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    尝试像auth()->check()(删除'\')或Auth::check(),这样它会是:

    if (Auth::check()) {
            return (FavouritePharmacy::where('user_id', Auth::user()->id)->where('pharmacy_id', $this->id)->count() == 1) ? 1 : 0;
        }
    

    并在模型顶部导入Auth,

    use Auth;

    【讨论】:

    • 同样的东西,返回null
    • 想到的一件事是 auth 中间件本身,请确保调用此方法的任何路由或页面都有为其定义的 auth 中间件。
    【解决方案2】:

    问题是我正在尝试从 api 检查 auth()。所以我应该添加 'api' giurd

    \auth()->check('api')
    

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 2020-04-20
      • 2016-05-31
      • 2020-09-05
      • 1970-01-01
      • 2015-09-06
      • 2016-04-22
      • 2019-10-01
      • 2016-05-07
      相关资源
      最近更新 更多