php - Laravel 7 __construct 中的用户数据

标签 php laravel laravel-7

使用 Laravel 7。 在 Controller 构造函数中,我希望能够访问当前用户详细信息,以便我可以将主站点小部件(按钮链接等)和自定义用户小部件加载到要在 View 中显示的一个中

use Illuminate\Support\Facades\Auth;

...

    $widgets = Cache::get("widgets");
    $usersdata = Cache::get("userdata");
    $this->middleware('auth');
    $widgets = array_merge($widgets, $usersdata[Auth::user()->id]["widgets"]);
    View::share([
        "widgets" => json_encode($widgets)
    ]);

但是,在现阶段的研究中,用户数据不可用(即使在身份验证之后?)。 不确定访问它的最佳方法,或者更好的做法可能是覆盖中间件身份验证(在哪里?),以便它可以返回用户 ID 或其他内容,例如:

$userid=$this->middleware('auth');

我希望在构造函数中使用此方法,以便扩展此主 Controller 的所有 Controller 都使用相同的方法。

最佳答案

这是 Laravel 的预期行为,您可以阅读更多相关信息 here .

Laravel collects all route specific middlewares first before running the request through the pipeline, and while collecting the controller middleware an instance of the controller is created, thus the constructor is called, however at this point the request isn’t ready yet.

你可以找到泰勒背后的推理here :

It’s very bad to use session or auth in your constructor as no request has happened yet and session and auth are INHERENTLY tied to an HTTP request. You should receive this request in an actual controller method which you can call multiple times with multiple different requests. By forcing your controller to resolve session or auth information in the constructor you are now forcing your entire controller to ignore the actual incoming request which can cause significant problems when testing, etc.

因此,一种解决方案是 create a new middleware然后将其应用于所有路由,如下所示,其中 widgets 是您的新中间件:

Route::group(['middleware' => ['auth', 'widgets']], function () {
    // your routes
});

但是如果您确实想将其保留在构造函数中,您可以实现以下解决方法:

class YourController extends Controller
{
    public function __construct(Request $request)
    {
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            $widgets = Cache::get("widgets");
            $usersdata = Cache::get("userdata");
            $widgets = array_merge($widgets, $usersdata[$request->user()->id]["widgets"]);

            View::share([
                "widgets" => json_encode($widgets)
            ]);

            return $next($request);
        });
    }
}

关于php - Laravel 7 __construct 中的用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62387697/

相关文章:

php - 将最新消息标记为... "new"

php - 登录表单不创建 POST 数据

php - 嵌套资源 Controller laravel 4

php - 新的 Laravel 项目抛出 500 错误 : require(): Failed opening required autoload. php

laravel-7 - Laravel Sanctuary 未经验证

php - 如果我想包含另一个文件夹,如何获取链接路径

javascript - 使 Youtube 360​​ 度视频在移动设备上运行

javascript - 在 Blade 模板中将 PHP 变量传递给 JavaScript

reactjs - Laravel 7 + React 渲染错误 : Nothing was returned from render

laravel - 无法重新启动 supervisor.service : Unit not found CentOS 7