dt2002 2018-03-09 14:53
浏览 80

Laravel 5:Auth :: id()在AppServiceProvider.php中返回NULL

I am trying to set a global variable in the AppServiceProvider.php file in Laravel 5. However, I cannot query a database which uses the currently logged in user ID. The Auth::id() returns null.

here is my code;

<?php

namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{

    public function boot()
    {
        $cnv_count = Conversation::where('receiver_id', Auth::id())->count(); // This Auth::id() here returns null

        view()->share(['cnv_count' => $cnv_count]);
    }


    public function register()
    {

    }
}

It doesn't return any error but when I try printing the the Auth::id() in the AppServiceProvider.php file, it always returns NULL.

what am I doing wrong here?

Appreciate the help guys.

  • 写回答

1条回答 默认 最新

  • dozc1071 2018-03-10 11:00
    关注

    I believe you're using an updated Laravel 5 version. You may want to consider this kind what i'm using to detect an authenticated user.

    add this above your class.

    use Illuminate\Support\Facades\Event;
    use Illuminate\Auth\Events\Authenticated;
    

    call this inside the class method.

    Event::listen(Authenticated::class, function ($event) {
               $this->data['auth'] = $event->user;
            });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算