0

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

Auth::user()->id

但是当我把它放在 AppServiceProvider.php 中时,它会返回“试图获取非对象的属性 'id'

我不明白为什么?

Eddit:我试过了,但还是不行

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 必须是数组类型,给定字符串,调用

4

2 回答 2

0

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

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

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

确保有用户登录。

于 2018-11-10T21:10:10.220 回答
-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());
    }
}
于 2019-05-25T12:11:08.907 回答