保存当前登录用户到控制器中的$this-user属性中

首先,要知道的是,控制器实例化的时候,用户模块还没启动呢,Reuqest 中的 user () 以及auth()->user是靠后期注入进来的

通过中间件来完成

修改默认laravel生成Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    protected $user;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
    }
}

这样,在每个控制器中就可以用$this->user访问啦

Last modification:January 31st, 2021 at 11:00 am
哎呀呀,大家随意,随意就好!