Kim Carlo
Kim Carlo

Reputation: 1223

Laravel 5: Auth::id() returns NULL in AppServiceProvider.php

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.

Upvotes: 0

Views: 439

Answers (1)

Kenneth Sunday
Kenneth Sunday

Reputation: 895

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;
        });

Upvotes: 1

Related Questions