M a m a D
M a m a D

Reputation: 2139

Laravel 5.7 - Access Auth::User() inside a service provider

I need to access to the current user in a service provider of a module. The Auth::user() returns null. I know the middleware is called after the service provider and that is why this is null. Is there any solution to this problem? it is my code

namespace Modules\User\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Facades\Module;

class ViewComposerProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */

    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */

    public function boot()
    {
        $this->buildMenu();
        $this->buildAvatar();
    }

    public function register()
    {
        dd(Auth::user());//null
    }

    private function buildAvatar(){
        $f = Auth::user();
        dd($f); // null
    }

    public function buildMenu()
    {
        view()->composer('layouts.subnavbar', function ($view) {
            $t = \Nwidart\Modules\Facades\Module::getByStatus(1);
            $modules = [];
            foreach ($t as $item)
                $modules[] = $item->name;
            $view->with('modules', $modules);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}

Upvotes: 1

Views: 2356

Answers (1)

MrChrissss
MrChrissss

Reputation: 291

Instead of calling the user in the provider you could make 2 view composers, 1 for the menu and 1 for the avatar

AvatarComposer.php

class AvatarComposer
{

    public function compose(View $view)
    {
        $avatar = Auth::user()->avatar//AVATAR HERE
        $view->with('avatar', $avatar);
    }
}

ModuleComposer.php

class ModuleComposer
{
    public function compose(View $view)
    {
        $t = \Nwidart\Modules\Facades\Module::getByStatus(1);
        $modules = [];
        foreach ($t as $item)
            $modules[] = $item->name;
        $view->with('modules', $modules);
    }
}

and then in the boot of your provider:

//make it public for all routes
View::composer('*', AvatarComposer::class);

View::composer('layouts.subnavbar', ModuleComposer::class);

Upvotes: 2

Related Questions