Laravel - How to get current user in AppServiceProvider
Asked Answered
P

3

36

So I am usually getting the current user using Auth::user() and when I am determining if a user is actually logged in Auth::check. However this doesn't seem to work in my AppServiceProvider. I am using it to share data across all views. I var_dump both Auth::user() and Auth::check() while logged in and I get NULL and false.

How can I get the current user inside my AppServiceProvider ? If that isn't possible, what is the way to get data that is unique for each user (data that is different according to the user_id) across all views. Here is my code for clarification.

if (Auth::check()) {
        $cart = Cart::where('user_id', Auth::user()->id);
        if ($cart) {
            view()->share('cart', $cart);

        }
    } else {
        view()->share('cartItems', Session::get('items'));
    }
Placeeda answered 22/5, 2016 at 8:56 Comment(1)
You need to create a custom middleware for this, see the discussions: laracasts.com/discuss/channels/laravel/…, github.com/laravel/framework/issues/7906Epicalyx
M
65

Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute before the middleware in the request lifecycle

You should use a middleware to share your varibles from the session

However, If for some other reason you want to do it in a service provider, you can do it using a view composer with a callback, like this:

public function boot()
{
    //compose all the views....
    view()->composer('*', function ($view) 
    {
        $cart = Cart::where('user_id', Auth::user()->id);
        
        //...with this variable
        $view->with('cart', $cart );    
    });  
}

The callback will be executed only when the view is actually being composed, so middlewares will be already executed and session will be available

Mild answered 22/5, 2016 at 10:55 Comment(4)
Just a note, I tried doing this today (Laravel 5.4) and it would not work with a closure as indicated in this answer. Providing a class name to an external object, e.g. view()->composer('*', \App\Http\ViewComposers\MyComposer::class) was the only way I could get it to recognize Auth::user() as anything but null.Translucid
how I can achieve same when using APIs as their are not blade/view used when using Laravel API'sDemonography
yeah this approach worked for mePinnatisect
This is great It works for Laravel 9 too.Maddox
H
19

In AuthServiceProvider's boot() function write these lines of code

public function boot()
{
    view()->composer('*', function($view)
    {
        if (Auth::check()) {
            $view->with('currentUser', Auth::user());
        }else {
            $view->with('currentUser', null);
        }
    });
}

Here * means - in all of your views $currentUser variable is available.

Then, from view file {{ currentUser }} will give you the User info if user is authenticated otherwise null.

Hau answered 14/12, 2017 at 6:19 Comment(4)
I want to share my cart data to all pages , it's helped me lotSegregationist
Nice solution, although I'd suggest not putting in AuthServiceProvider as boot() should be limited to registering authentication and authorization services. Maybe AppServiceProvider or even ComposerServiceProvider?Hebetate
how I can achieve same when using APIs as their are not blade/view used when using Laravel API'sDemonography
@AbhiBurk in api, you've to definitely pass a token to get data. I'm not sure if that can be done in AppServiceProvider.Hau
P
-1

As per my Laravel 7 experience, Auth::user() does not work in AppServiceProvider.php instead the helper function auth()->user() did the trick for me.

public function boot()
    {

        if (auth()->check()) {
            View::composer('layout.app', function ($view) {
                $userName = auth()->user()->name;
                $view->with(['userName' => $userName]);
            });
        }
    }
Pastoralist answered 5/6, 2021 at 10:39 Comment(1)
it doesn't work in laravel 8Vinia

© 2022 - 2024 — McMap. All rights reserved.