Leguam
Leguam

Reputation: 1212

Laravel Auth::user not found in other controller

When a user is registered an email is send to the user email with an activation link (auth_code) which links to this function:

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]);
}

So the user will log in.

Now there is my problem. Via the UserConstructor it wil lead to the 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);
}

Which leads to this error: enter image description here

And when I do Auth::check() inside the CompanyController it will return false, so somehow it will log the user off in the process, what is going wrong?

(Auth::check() in the confirmUser will give true as result)

Upvotes: 4

Views: 914

Answers (2)

Jakir Hossen
Jakir Hossen

Reputation: 461

I did send it with a hidden input field. Try to do it this way:

<input id="email" type="hidden" name="email" value="{{ Auth::user()->email }}" required> 

Mine works perfectly.

Upvotes: 0

Luceos
Luceos

Reputation: 6730

From what I read. You are instantiating the UserController with the parameter CompanyController.

This instantiation is done before you have actually send the Auth::login() call.

As you are instantiating the company controller with __construct before running confirmUser on the userController the object companyController exists before the Auth::login() call is made.

Upvotes: 2

Related Questions