如何在所有 laravel 视图中共享经过身份验证的用户

How to share the authenticated user across all laravel views

我在 Laravel 5.8 中遇到了一个非常奇怪的问题。我想与所有视图共享用户变量。

我在 AppServiceProvider.php 中将此添加到我的 boot 方法中:

Event::listen(Authenticated::class, function ($e) {
    view()->share('user', $e->user);
});

在视图中,我有这个:

@auth('web')
  {{$user->name}}
@endauth

User 型号有

protected $guard = 'web';

大部分时间都有效,但有时我会收到此错误:

Uncaught ErrorException: Undefined variable: user in /home/forge/www.mywebsite.com/storage/framework/views/4b273b493839e5fb54c3f6a2d11d9446bee5de33.php:11

怎么可能?

您可以在您的视图中通过 auth 助手访问经过身份验证的用户。

$user = auth()->user();

https://laravel.com/docs/5.8/helpers#method-auth

更新:为了不在每个视图中重复此操作,您可以从布局文件中的 auth facade/helper 获取用户,这样变量将在扩展该布局的所有视图中可用

只需在 blade 中使用全局 auth() 方法来获取经过身份验证的用户信息。

@auth {{ auth()->user->id }} @endauth

@auth {{ auth()->user->name }} @endauth

@auth {{ auth()->user->email }} @endauth

如果需要,您可以指定要访问的守卫实例:

$user = auth('web')->user();

已更新

有时,您可能需要与应用程序呈现的所有视图共享一段数据,请查看以下内容link

Sharing Data With All Views

所有这些都是很好的答案。您也可以使用 Auth facade 来完成此操作。

use Illuminate\Support\Facades\Auth;

$user = Auth::user()->name;

https://laravel.com/docs/5.8/authentication

考虑对视图周围的共享变量使用视图编辑器

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Contracts\Auth\Guard; 
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Guard $auth)
    {

        // Using Closure based composers...
        View::composer('*', function ($view) use ($auth) {
            $view->with('currentAuthenticatedUser', $auth->user());
        });
    }
}

Docs