简体   繁体   English

在Laravel ComposerSeriveProvider中使用Auth :: user()

[英]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: 我正在使用ComposerServiceProvider在视图中设置用户数据:

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. 但是正如文档所述,此方法将在其他服务(如Auth)之前加载,因此Auth::check()在这里无法正常工作。 As they also wrote about this: https://github.com/laravel/framework/issues/7600 正如他们也写的那样: https : //github.com/laravel/framework/issues/7600

How can I achieve to use ViewComposers with checking the user authentication? 如何在检查用户身份验证时使用ViewComposers Also any other suggestion appriciated. 也有其他建议。

In your boot function Auth is not yet available, that's correct. 在您的启动功能中, Auth尚不可用,这是正确的。

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. 在这种情况下,如果$auth->user()应该为null (如果没有用户登录,则为null ),并且也可以在模板中检查isNull($topics) ,则我可能还会重构getRecentFollowingTopics函数以返回null

Also, did you know that in Laravel 5 you can inject classes directly into blade like this: 另外,您是否知道在Laravel 5中可以将类直接注入到Blade中,如下所示:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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