DEV Community

Cover image for How to Login Users With Phone Number or Username in Laravel
Ikechukwu Vincent
Ikechukwu Vincent

Posted on

How to Login Users With Phone Number or Username in Laravel

Welcome to the world of Laravel, a popular PHP framework for web application development. In this article, we will be discussing the process of logging in with either a phone number or username in Laravel. Laravel implemented email login out of the box, however, developers tend to struggle when there is a need to log in with any other user bio data like username or phone number

As with everything in programming, there are many ways to do it. However, there is a defined laravel way to do it - which is in fact best practice and more secure.

Before we proceed, I have a word for you as a laravel developer or developer working with laravel, make the doc your best friend.

Lets begin!

We begin by altering user table migration file to add the bio data of interest. This bio data(phone or username) will have to be unique for the table - no two users in same table can have same phone or username.

php artisan make:migration add_cols_to_users_table
Enter fullscreen mode Exit fullscreen mode

Now let us add the table columns to the file


Enter fullscreen mode Exit fullscreen mode

NB: In your registration page, these fields are must for users fill them in. And they must be unique to the table.

In laravel default login blade page, email input field have the name value of email. Change it to anything you want, I normally use "identifier".

Now let us proceed to the controller method that handles user login.

   if (Auth::guard('web')->attempt(['email' => $request->identifier, 'password' => $request->password])|| 
        Auth::guard('web')->attempt(['phone' => $request->identifier, 'password' => $request->password])) {
            // Authentication was successful...
            // Auth::guard('web')->login($user);
            return redirect()->intended(RouteServiceProvider::HOME);
            return redirect()->route('login')->with('fail','Incorrect credentials');

Enter fullscreen mode Exit fullscreen mode

That will be all, now navigate to your login page, and login either with email or phone number.

If you would like to add username to the authentication parameters, all you need to is to add one more "Or" to the if statement of the login method. Just the way I did it for phone.

To gain deep understanding how this work behind the scene, read more about Laravel Authentication Auth Facade
and also about authentication guards in laravel.

I am Vincent Ikechukwu, Full Stack Web Developer and Software Engineer. Connect with me on social media via links below.

If you run into trouble leave a comment or say hi on my social media.

Top comments (0)