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

zerosAndOnes's avatar

Laravel: login with username or email issue

Not sure if this belongs here or in the eloquent channel.

I am having an issue that I don't even understand how to go about fixing.

I am passing in a form field named emailOrUsername, then using the where and orWhere queries to check two columns in a table, but I get an error that uses the request field/param name as the column not found.

$user = User::where('username', $request->emailOrUsername)
                    ->orWhere('email', $request->emailOrUsername)
                    ->first();

Error:

"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emailOrUsername' in 'where clause' (Connection: mysql, SQL: select * from `users` where `emailOrUsername` = wuceruda limit 1)",
  "exception": "Illuminate\Database\QueryException",

Note: When I send a wrong (not a valid user) emailOrUsername value, I do get a response of wrong credentials

I do have the username and email columns on the users table.

0 likes
12 replies
LaryAI's avatar
Level 58

It seems like the error you're encountering is not directly related to the query you've written, but rather an issue with how the query is being interpreted or executed by Laravel's Eloquent ORM. The code snippet you provided looks correct for querying a user by either their username or email. However, the error message suggests that somewhere in your code, a query is being run that is incorrectly using emailOrUsername as a column name.

To troubleshoot this issue, ensure that you are passing the correct value from your request to the query and that no other part of your code is attempting to use emailOrUsername as a column name. Here's a revised version of your code snippet with added request validation to ensure that the emailOrUsername field is being received correctly:

// First, validate the request to ensure 'emailOrUsername' is present
$request->validate([
    'emailOrUsername' => 'required|string',
]);

// Then, attempt to retrieve the user by username or email
$user = User::where('username', $request->emailOrUsername)
            ->orWhere('email', $request->emailOrUsername)
            ->first();

// Check if a user was found
if ($user) {
    // User found, proceed with login or other actions
} else {
    // No user found, handle accordingly
}

If you're still encountering the same error after this, it might be helpful to log the actual SQL query being executed to see if there's an issue with how the query is being constructed. You can do this by listening for the Illuminate\Database\Events\QueryExecuted event and logging the SQL and bindings:

// Place this in your AppServiceProvider or another service provider's boot method
\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    \Log::info($query->sql);
    \Log::info($query->bindings);
});

This will log the SQL queries to your Laravel log file, which you can then inspect to see if there's an unexpected query being executed that's causing the error.

Remember to remove or comment out the event listener once you've resolved the issue, as logging all queries can have performance implications and may expose sensitive information in your logs.

Tray2's avatar

I highly suggest that you don't write your own login, but instead use either Laravel Breeze, or Laravel JetStream.

DhPandya's avatar

So, After verifying successfully from the database there is some further logic that is trying to read data again?

Note: When I send a wrong (not a valid user) emailOrUsername value, I do get a response of wrong credentials
zerosAndOnes's avatar

@DhPandya No! what I meant was that I only get the column issue when the value of emailOrUsername exists.

I changed the request param to just email and it started working. But I am confused because when I echo $user from my example above, a user is actually returned, but the error is still there.

zerosAndOnes's avatar

@DhPandya

public function login(Request $request)
    {
        $credentials = $request->validate([
            'emailOrUsername' => 'required',
            'password' => 'required',
        ]);

        $user = User::where('email', $request-> emailOrUsername)
                    ->orWhere('username', $request-> emailOrUsername)
                    ->first();

        echo($user);

        if ($user && Auth::attempt($credentials)) {
                $user = Auth::user();
                $user->createToken('_token')->plainTextToken;
     
                return response()->json([
                    "message" => "Successfully logged in.",
                ], 200);
            }

        return response()->json([
            "message" => "The provided credentials do not match our records."
        ], 404);
    }
DhPandya's avatar

@zerosAndOnes This is the mistake.

Auth::attempt($credentials));

In your $credentials array you have a key emailOrUsername which is passed to auth. So while checking with the database it throws an unknown column exception. Either use your logic or Auth::attempt.

zerosAndOnes's avatar

@DhPandya How so? This works if I only look up one column on the table. So doing the below without changing anything else, works:

$credentials = $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);

        $user = User::where('email', $request-> email)->first();
zerosAndOnes's avatar

@DhPandya Interesting. I guess this is why it works with a column it knows. It thinks emailOrUsername is a column. What will a work-around be?

DhPandya's avatar
DhPandya
Best Answer
Level 12

@zerosAndOnes Alternate solution:

Auth::attempt(['email'=>$user->email,'password'=>$credentials['password']])

Now if you want to check with the columns between username and email try adding a logic by checking which one contains data from the $user object.

Please or to participate in this conversation.