【问题标题】:Laravel | Auth::user()->id isn't working in AppServiceProvider拉拉维尔 | Auth::user()->id 在 AppServiceProvider 中不起作用
【发布时间】:2019-04-13 23:04:04
【问题描述】:

当我将其放入任何控制器中时,我可以获得 Auth ID

Auth::user()->id

但是当我把它放在 AppServiceProvider.php 中时,它会返回 `Trying to get property 'id' of non-object

我不明白为什么?

编辑:我试过了,但还是不行

public function boot()
{
    view()->composer('*', function ($view) 
{
if (Auth::check())
{
    $id=Auth::user()->id;
    $idd=Person::where('user_id','=',$id)->get('photo');

    $view->with('idd', $idd );
    $view->with('id', $id );
}
       });
}

错误: 传递给 Illuminate\Database\Grammar::columnize() 的参数 1 必须是数组类型,给定字符串,在

中调用

【问题讨论】:

标签: laravel


【解决方案1】:

要获取当前经过身份验证的用户 ID,请使用 Auth::id();

另一种情况可能是没有当前用户,在这种情况下Auth::user() 返回 NULL。将代码包装在

if (Auth::check())
{
    // Do stuff
}

确保有用户登录。

【讨论】:

  • 编辑了答案,你有当前用户吗?
  • 我再次编辑帖子时出现了新的错误消息,您可以检查一下吗?
【解决方案2】:

这对我有用

<?php

namespace Fitness\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Request $request)
    {
    view()->share('user', $request->user());
    }
}

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 2014-03-06
    • 2016-03-19
    • 1970-01-01
    • 2017-09-02
    • 2017-02-07
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多