我需要访问模块服务提供商中的当前用户。 Auth::user()
返回null。我知道中间件是在服务提供者之后调用的,这就是为什么它为null的原因。有什么解决办法吗?这是我的代码
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 [];
}
}
答案 0 :(得分:2)
您可以制作2个视图作曲家,而不是在提供者中致电用户,其中1个用于菜单,而1个用于头像
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);
}
}
,然后在提供者的boot
中:
//make it public for all routes
View::composer('*', AvatarComposer::class);
View::composer('layouts.subnavbar', ModuleComposer::class);