【问题标题】:How do I create a Laravel global variable from session data and make available across all views?如何从会话数据创建 Laravel 全局变量并在所有视图中可用?
【发布时间】:2019-08-05 16:26:06
【问题描述】:

我在 LoginController 中设置登录时的会话数据,如下所示:

class LoginController extends Controller{
    protected function authenticated($request, $user){
       $record = ['name'=>'bob'];
       session(['profile' => $record]);
    }
}

会话在任何刀片中都可用:

$profile = session('profile');

如何让变量$profile 在所有刀片上都可用?

我曾尝试使用事件监听器和View::share( 'profile', session('profile')),但在我使用的事件中似乎无法访问会话数据。

【问题讨论】:

    标签: laravel laravel-events laravel-session


    【解决方案1】:

    您正在寻找的是视图作曲家:

    https://laravel.com/docs/5.8/views#view-composers

    如果您的会话数据在服务提供者的启动过程中不可用(它不是),您应该使用中间件并以这种方式定义它:

    https://laravel.com/docs/5.8/middleware#registering-middleware

    // App\Http\Middleware\MyMiddleware.php
    class MyMiddleware
    {
        public function handle($request, Closure $next, $guard = null)
        {
            $profile = session('profile');
            View::share('profile', $profile);
    
    
            // Important: return using this closure,
            // since this is all part of a chain of middleware executions.
            return $next($request);
        }
    }
    

    接下来确保您的中间件已加载到 App\Http\Kernel.php 中(例如在全局中间件堆栈 protected $middleware = [...] 中。

    【讨论】:

    • 谢谢您 - 现在阅读这两篇文章。您能否澄清一下:“应该使用中间件并以这种方式定义它。”在 AppServiceProvider 中,我在 boot() 中添加了以下内容:$profile=session('profile'); View::share('profile', $profile); 并且我已经为所有请求注册了一个全局中间件 - 但我不清楚我应该在 ServiceProvider 中定义什么以及如何定义。
    • 我编辑了答案并添加了一个中间件示例
    【解决方案2】:

    正确的做法是使用这句话 session()->get('profile'),例如在视图 {{ session()->get('profile') }} 中。

    【讨论】:

    • 谢谢 - 正确,它返回刀片内的会话数据。我想在刀片运行之前将 session('profile') 设置为全局变量 $profile,以便在刀片中,开发人员可以轻松地使用 $profile 而不是更冗长的 session(...)
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2018-01-09
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多