Home > Enterprise >  How to access currently logged in user globally in Laravel, Auth::user() returning null
How to access currently logged in user globally in Laravel, Auth::user() returning null

Time:10-29

When a user is logged in, session('person_id') is set, but Auth::user() returns null.

This means I have to do this everywhere I need access to properties or methods of the user:

$person  = Person::where('id', session('person_id'))->firstOrFail();

What is a better solution for this? Could I set $person in the BaseController then access the user via $this->user when I need it?

I don't want to do a DB query for every request on every page. Using Laravel 8 with PHP 8.

Here are my current login and signup functions:

 /**
 * Handles user login
 *
 * @param  Request $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function login(Request $request)
{
    $credentials = $request->validate([
        'email'    => ['required', 'email'],
        'password' => ['required'],
    ]);

    if (Auth::attempt($credentials, request('remember'))) {
        $request->session()->regenerate();

        return redirect()->intended('/account')->with('status', 'Logged in');
    }

    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

/**
 * Saves a new unverified user, sends code to their email and redirects to verify page
 *
 * @param  Request $request
 */
public function signUp(Request $request)
{
    // @todo Move to SignUpRequest file
    $request->validate([
        'email'    => 'required|email|unique:people',
        'password' => 'required',
    ]);

    $person           = new Person; 
    $person->email    = $request->email;
    $person->password = Hash::make($request->password);

    if (!$person->save()) {
        return back()->with('status', 'Failed to save the person to the database');
    }

    $request->session()->put('person_id', $person->id);

    $verification             = new Verification;
    $verification->person_id  = $person->id;
    $verification->code       = rand(111111, 999999);
    $verification->valid_from = Carbon::now();
    $verification->expires_at = Carbon::now()->addDay();

    if (!$verification->save()) {
        return back()->with('status', 'Failed to save the verification to the database');
    }

    // email stuff
    
    return redirect('/verify')->with('status', 'Successfully created account, please verify to continue');
}

CodePudding user response:

It seems your fighting with framework default authentication you're using another model instead of User I recommend reading the official documentation You can take a look at laravel breeze to see how they implemented authentication if you check the laravel breeze you'll see you missed the Auth::login($user)

 public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        Auth::login($user);

        return redirect(RouteServiceProvider::HOME);
    }

CodePudding user response:

Laravel ships with a the global helper auth() and you can access the logged user with auth()->user()

  • Related