php – Laravel Auth ::在其他控制器中找不到用户

当用户注册时,会向用户发送电子邮件,其中包含链接到此功能的激活链接(auth_code):

public function confirmUser($authentication_code)
{
    if (!$authentication_code) {
        return 'auth code not found!';
    }

    $user = User::where('authentication_code', '=', $authentication_code)->first();

    if (!$user) {
        return 'user not found!';
    }

    $user->active = 1;
    $user->save();

    Session::put('user_id', $user->id);

    Auth::login($user);

    return view('user.setpassword', ['user' => $user]);
}

所以用户将登录.

现在有我的问题.通过UserConstructor,它将导致CompanyController

//UserController
public function  __construct(User $user, CompaniesController $companies, UserTypeController $userType, AttributeController $attributes)
{
    $cid = Auth::user()->company_id;

    if (Auth::user()->usertype_id == 7) {
        $this->user = $user;
    }
    else
    {
        $array_company_ids = $companies->getCompany_ids($cid);
        $this->user = $user->whereIn('company_id', $array_company_ids);
    }

}

//CompanyController
public function __construct(Company $company)
{
    if (Auth::user()->usertype_id == 7) {
        $this->company = $company;
    } else {
        $this->company_id = Auth::user()->company_id;
        $this->company = $company->Where(function ($query) {
            $query->where('id', '=', $this->company_id)
                ->orWhere('parent_id', '=', $this->company_id);
        });
    }

    $this->middleware('auth');

    $page_title = trans('common.companies');
    view()->share('page_title', $page_title);
}

这导致了这个错误:

当我在CompanyController中执行Auth :: check()时,它将返回false,因此它会在某个过程中将用户注销,出现了什么问题?

(confirmUser中的Auth :: check()结果为true)

最佳答案 从我读到的.您正在使用参数CompanyController实例化UserController.

在实际发送Auth :: login()调用之前完成此实例化.

当您在userController上运行confirmUser之前使用__construct实例化公司控制器时,对象companyController在进行Auth :: login()调用之前就存在了.

点赞