事件监听器中Inertia::share失效,无法全局共享动态菜单
问题原因
登录事件监听器里调用Inertia::share仅对当前登录请求生效,但登录操作完成后通常会触发重定向,新请求的上下文不会继承之前共享的数据,导致菜单无法在后续页面显示。
解决方案
方案一:在服务提供者中动态共享菜单(推荐)
将菜单共享逻辑放到AppServiceProvider的boot方法中,每次页面渲染时自动判断用户状态并生成菜单:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Inertia\Inertia; class AppServiceProvider extends ServiceProvider { public function register(): void { // } public function boot(): void { Inertia::share('menu', function () { // 未登录时返回空数组,避免前端报错 if (!auth()->check()) { return []; } // 可根据用户权限动态生成菜单 return [ ['label' => 'Home', 'url' => '/'], ['label' => 'About', 'url' => '/about'], ['label' => 'Contact', 'url' => '/contact'], // 扩展更多菜单项 ]; }); } }
方案二:登录时存Session,服务提供者共享
如果菜单需要依赖登录时的临时数据生成,可先存入Session,再全局共享:
- 修改登录事件监听器:
<?php namespace App\Listeners; use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Session; class LogAuthenticatedUser { public function handle(Login $event) { $menu = [ ['label' => 'Home', 'url' => '/'], ['label' => 'About', 'url' => '/about'], ['label' => 'Contact', 'url' => '/contact'], ]; Session::put('user_menu', $menu); } }
- 在
AppServiceProvider中共享Session数据:
public function boot(): void { Inertia::share('menu', function () { return Session::get('user_menu', []); }); }
内容的提问来源于stack exchange,提问作者Jeeva K
相关产品推荐
相关产品推荐

