在laravel中为整个应用程序持久化一个变量


Persist a variable for the entire application in laravel

我正在研究一个旨在显示学生记录的应用程序,显然要查看和编辑记录,我必须选择一个学生。我想知道如何存储学生的id在一个全局变量或类似的东西。为了使它在应用程序的任何部分都可以从任何控制器或视图中使用它,并且一旦应用程序的用户关闭或显示另一个记录,这个变量被加载为新的Id

知道怎么做吗

这是概念和想法。考虑到您正在存储每个学生的数据,并且每个学生都必须有登录帐户的用户名和密码。

得到认证用户的id,比如
Auth::student()->id; // For logged in user we do Auth::user()->id;

现在你想要的是全局共享这个ID,所有控制器和视图都可以访问,为此你需要编辑AppServiceProvider,并在boot函数中获取认证的用户,并像下面这样全局共享它。

public function boot()
{
        $studentID = Auth::student()->id; // grab the ID you want to share globally
        view()->share('studentID', $studentID);
}

确保您添加了导入您正在使用的模型。

现在你可以在任何地方访问认证的学生ID,像这样

{{ $studentID }} //this will echo the authenticated student ID

尝试全局可用的session函数:

session(['studentID'=>Auth::student()->id]);

然后像这样访问:

session('studentID');

在视图中:

{{ session('studentID') }}