[英]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 獲取用戶,這樣該變量將在擴展該布局的所有視圖中可用
只需在您的刀片中使用 global auth()
方法來獲取經過身份驗證的用戶信息。
@auth {{ auth()->user->id }} @endauth
或者
@auth {{ auth()->user->name }} @endauth
或者
@auth {{ auth()->user->email }} @endauth
如果需要,您可以指定要訪問的守衛實例:
$user = auth('web')->user();
更新
有時,您可能需要與應用程序呈現的所有視圖共享一段數據,請查看以下鏈接
考慮對視圖周圍的共享變量使用視圖編輯器
<?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());
});
}
}
所有這些都是很好的答案。 您還可以使用 Auth 外觀來完成此操作。
use Illuminate\Support\Facades\Auth;
$user = Auth::user()->name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.