Laravel authenticate with username or email
In this article “Laravel authenticate with username or email” we will discuss about authenticate user with username or email in just one field. Laravel provide different tools to make development easier but by default laravel provide authentication only with email.
If it’s your first time with laravel you should check those articles who are required to follow this article.
- Complete guide to install laravel 5.8 on linux
- How to Setup Laravel Authentication in few Simple Step
Step 1 – Upgrade migration
As we already make the first login in the article How to Setup Laravel Authentication in few Simple Step we have to update the migration and add the field username. Now our migration look like this :
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
Now for adding a new field in this migration we could just update it and re run the migration but that’s will erase all our data. Laravel provide a good way to update migration. Open a terminal at the roof of the project and execute this command.
php artisan make:migration --table=users add_username_to_users
This command create a new migration for the table users and now we can start adding the column we want. You can know more about migration by following this link to Laravel Documentation
After adding the column username your migration should look like this. And you will find this migration file under database > migration.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddUsernameToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('username')->unique(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { // }); } }
After updating the migration time to execute the migrate command.
php artisan migrate
Now our database should be ready for the next step but let’s take care of our user model.
Step 2 – Update user model
Now, time to update User model. Open your User Model (app/User.php) and add the username column in the fillable array.
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'username' ];
We are adding it here to avoid raising mass assignment exception you can find out more in this link Mass Assignment.
Step 3 – Update blade template
After we updated the database and the user model we have to edit blade template to add username field to register and login.
Step 3.1 – Register template
Open register.blade.php located at “resources/views/auth/”, Add the following code after the name row to add a username input field.
<div class="form-group row"> <label for="username" class="col-md-4 col-form-label text-md-right"> {{ __('Username') }} </label> <div class="col-md-6"> <input id="username" type="text" class="form-control{{ $errors->has('username') ? ' is-invalid' : '' }}" name="username" value="{{ old('username') }}" required=""> @if ($errors->has('username')) <span class="invalid-feedback"> <strong>{{ $errors->first('username') }}</strong> </span> @endif </div> </div>
This snippet is not complicated it’s just a field to add username in the register form following the laravel way and let’s see the result in the following screen.

Step 3.2 – Login template
First we need to make some changes to the login view particularly in E-Mail Address input field row. Open login.blade.php located at “resources/views/auth/” directory. Now replace the first row in the form which the E-Mail Address input field with the contents below.
<div class="form-group row"> <label for="login" class="col-sm-4 col-form-label text-md-right">{{ __('Username or Email') }}</label> <div class="col-md-6"> <input id="login" type="text" class="form-control{{ $errors->has('username') || $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('username') ?: old('email') }}" required="" autofocus=""> @if ($errors->has('username') || $errors->has('email')) <span class="invalid-feedback"> <strong>{{ $errors->first('username') ?: $errors->first('email') }}</strong> </span> @endif </div> </div>

Now we can take care of our controller (back-end) to make sure we can login with username or email.
Step 4 – Update register controller
Front end is ready we only need the back-end logic. Go to RegisterController.php
file in app/Http/Controllers/Auth
directory. So edit the register to add new validation rules for the username and also add in the create methode.
<?php namespace App\Http\Controllers\Auth; use App\User; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after registration. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'username' => ['required','string','max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'username' => $data['username'], 'password' => Hash::make($data['password']), ]); } }
Do not forget to make the validation unique also for username.
Now we got all setup for the RegisterController.
Step 5 – Update login controller
Let’s setup back-end logic for our login. Go to LoginController.php
file present in app/Http/Controllers/Auth
directory. Open your Login Controller, here we only need to override one method called “credentials()”.
This method can be found at “Illuminate\Foundation\Auth\AuthenticatesUsers”. Laravel default authentication provides many methods to handle the authentication process. To apply any kind of customization we only need to override the credentials() method.
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } /** * Get the needed authorization credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(Request $request) { //Check if we have a valid email ortherwise take username as the variable $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL) ? $this->username() : 'username'; return [ $field => $request->get($this->username()), 'password' => $request->password, ]; } }
Let’s explain our overriding.
First we check if the variable username is a valid email. In case it’s valid so $this->username() do not change but in other case the username replace it and we return both item for the authentication.
Step 6 – Conclusion and test
In this article about “Laravel authenticate with username or email” we discuss about how we can do authentication with both username or email.
We could add phone number if we want but let’s talk about this in another article. I let you test this yourself.
If you have any question feel free to leave them in the comment section or on our social media.
Very Nice it works nicely .