Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jessiesanford's avatar

Authenticating user login from database not working

I'm new to Laravel and currently trying to port my vanilla web app over to it. I have a MySQL database with a user table: users => (user_id, group, first_name, last_name, password, email, phone, date, survey) as the schema. I'm trying to authenticate a login through AJAX, which seems to go through successfully when the proper credentials are provided, I even have a console log returning the row it's received from the database. This is the login function:

    public function login(Guard $auth)
    {
        if (Auth::attempt(['email' => $_POST['email'], 'password' => $_POST['password']])) {
            $user = $auth->getLastAttempted();
            error_log($user);
            Auth::login($user);
            $return_arr['alert'] = "Logging in...";
        }
        else {
            $return_arr['form_check'] = 'error';
            $return_arr['alert'] = "The username and password are incorrect.";
        }
        echo json_encode($return_arr);
    }

However when I go to the home page which has the auth middle ware

$this->middleware('auth');

It redirects me back to the login page, even though the authentication went through with no error. I'm going crazy trying to figure out such a trivial problem on my own and require a little assistance.

0 likes
2 replies
Snapey's avatar

Why are you calling login again? try;

    public function login(Guard $auth)
    {
        if (Auth::attempt(['email' => $_POST['email'], 'password' => $_POST['password']])) {
            $user = Auth::user();
            error_log($user->name);
            $return_arr['alert'] = "Logging in...";
        }
        else {
            $return_arr['form_check'] = 'error';
            $return_arr['alert'] = "The username and password are incorrect.";
        }
        echo json_encode($return_arr);
    }
1 like
jessiesanford's avatar

I actually figured it out, it was because I didn't change the primary key in the user model to 'user_id'

protected $primaryKey = 'user_id';

Thanks for your reply though!

Please or to participate in this conversation.