0

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');
}
2
  • Where are you attempting to use Auth::user()? It doesn't work in by itself in __construct() calls, but you can fudge it a bit Commented Oct 28, 2021 at 19:24
  • 1
    If I were you, I would focus on "fixing" why is it returning null instead of searching for a workaround. Have you seen this post, which explains some reasons why it would be returning null? stackoverflow.com/questions/35160144/authuser-returns-null Commented Oct 28, 2021 at 19:42

2 Answers 2

1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

-1

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

2 Comments

auth() and Auth:: point to the same thing
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.