Login with Username or Email with Laravel 10: Enhanced User Authentication

Introduction: Welcome back to my blog series on user authentication with Laravel! In my previous articles, we have covered the topic of login with username or email in different versions of Laravel. Today, I'm excited to bring you an updated approach specifically for Laravel 10. This enhanced functionality allows users to log in using either their username or email address, offering a more personalized login experience. If you're interested in exploring our previous articles on this topic in different Laravel versions, check them out in the "Also Read" section below.

Understanding the Need for Login with Username or Email: In traditional user authentication systems, the login process typically relies on a fixed field, either the email or username. However, as applications evolve, it's essential to provide users with the flexibility to choose their preferred login method. By implementing login with both username and email options, we can create a more user-friendly experience. Let's dive into the implementation details.


Prerequisites: Before getting started with the article below, it is recommended to have a solid understanding of Laravel, PHP and web development concepts. Familiarity with PHP programming, web basics (HTML/CSS/JavaScript), MVC architecture, databases, and basic command-line knowledge will be beneficial for effectively working with the Laravel framework.

Also Read:

Laravel 5.4: Login with Username or Email
Laravel v5.5: Login, Register with Username or Email
Laravel 5.6 Login, Register, Activation with Username or Email Support
Laravel 5.7: Adding Support for Login with Username or Email
Building a Password Less Authentication System with Laravel Signed Routes

Let's get started!

Step 1: Database Preparation To enable login with both username and email, we need to make modifications to our database. Open your migration file and add a new column, username, to the users table. Ensure the username column is unique and indexed.

Schema::table('users', function (Blueprint $table) {
    $table->string('username')->unique()->after('email');
});


Step 2: User Model Configuration Next, update the User model to include the username field in the $fillable array and implement a method to dynamically determine the login field.

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'name', 'email', 'password', 'username',
    ];

    public function getLoginField($loginValue)
    {
        return filter_var($loginValue, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
    }

    // ...
}


Step 3: Login Form Update your login form to include a single input field for both the username and email. Modify the login controller to handle the dynamic login field.

<form method="POST" action="{{ route('login') }}">
    @csrf

    <div>
        <label for="login">Username or Email</label>
        <input id="login" type="text" name="login" value="{{ old('login') }}" required autofocus>
    </div>

    <!-- Rest of the form fields -->

    <div>
        <button type="submit">Login</button>
    </div>
</form>


Step 4: Login Controller Modify your login controller to utilize the dynamic login field based on user input. By overriding the username() method, we can dynamically switch between the username and email fields during the authentication process.

use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    // ...

    public function username()
    {
        $loginValue = $this->request->input('login');
        $loginField = $this->guard()->user()->getLoginField($loginValue);

        return $loginField;
    }

    // ...
}

 

Inside the AuthenticatesUsers trait, there is a method called credentials() that is responsible for retrieving the login credentials from the request. In order to support login with both username and email, we need to modify this method to dynamically determine the login field based on the provided input.

Here's an updated version of the credentials() method:

/**
 * Get the login credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    $loginField = $this->getLoginField($request->input($this->username()));
    
    return [$loginField => $request->input($this->username()), 'password' => $request->input('password')];
}


You can easily override the credentials() method in the User model to customize the login process further. By doing so, you can handle any specific logic or validations related to the login credentials.

To override the credentials() method in the User model, follow these steps:

  • Open your User model file (usually located at app/Models/User.php).
  • Add the following code to override the credentials() method:
/**
 * Get the login credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function credentials(Request $request)
{
    $loginField = $this->getLoginField($request->input($this->username()));

    return [
        $loginField => $request->input($this->username()),
        'password' => $request->input('password'),
        'active' => true, // Customize additional conditions if needed
    ];
}

 

Customize the method as per your requirements. You can add extra conditions to the credentials array, such as checking for an active user or applying any other business logic.

By overriding the credentials() method in the User model, you have the flexibility to tailor the login process according to your application's needs.

Now, Laravel will use the overridden credentials() method from the User model instead of the default implementation.

That's it! With these advanced code snippets and modifications, your login system will now support login with both username and email options. Users can choose their preferred login method, enhancing the overall user experience.

Conclusion: In this article, we explored how to implement login with both username and email options using Laravel 10. By allowing users to choose their preferred login method, we create a more personalized and user-friendly experience. Remember to follow the step-by-step guide and update the necessary code snippets in your application.

I hope this advanced tutorial has been helpful in expanding your understanding of user authentication with Laravel 10. If you have any questions or comments, please feel free to leave them below. Stay tuned for more exciting Laravel tutorials and guides in the future!

References:

Laravel Documentation