简体   繁体   中英

Using Auth::user() in Laravel ComposerSeriveProvider

I have a sidebar, where I want to display logged in user's favorite topics.

I'm using ComposerServiceProvider to set user's data in the view:

public function boot(UserRepository $userRepository)
{
    if(Auth::check()) {
        view()->composer('common.sidebar', function ($view) use($userRepository) {
            $view->with('topics', $userRepository->getRecentFollowingTopics(Auth::user()));
        });
    }
}

But as the documentation says, this will loaded before other services, like Auth , so Auth::check() not working here. As they also wrote about this: https://github.com/laravel/framework/issues/7600

How can I achieve to use ViewComposers with checking the user authentication? Also any other suggestion appriciated.

In your boot function Auth is not yet available, that's correct.

However, in your closure it is! So just refactor your code to this:

// Notice the dependency injection of the Guard! Don't forget to import it on top of your Service Provider
public function boot(Guard $auth, UserRepository $userRepository)
{
    view()->composer('common.sidebar', function ($view) use($auth, $userRepository) {
        if($auth->check()) {
            $view->with('topics', $userRepository->getRecentFollowingTopics($auth->user()));
        }
    });
}

In this case I would also probably refactor your getRecentFollowingTopics function to return null if $auth->user() should be null (which it is, if no user is logged in) and just check for isNull($topics) in your template.

Also, did you know that in Laravel 5 you can inject classes directly into blade like this:

@inject('userRepository', 'App\UserRepository')

and then use it, for example, like this:

@if(!is_null($topics = $userRepository->getRecentFollowingTopics(auth()->user())))
    @foreach ($topics as $topic)
    ....
    @endforeach
@else
    show whatever you like
@endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM