How to login with username or email in Laravel authentication
I will give you a simple solution to Laravel login with username or email in the authentication. Laravel to easily make auth login with username and email address in Laravel application. and How to login with a name or email in Laravel.
We need to create a login page with a username or email address to login. the customer gets a username forgot email then he has one username.
Install Laravel
composer create-project --prefer-dist laravel/laravel blog
Install Laravel UI
Simple you need to install laravel/ui package bellow command:
composer require laravel/ui
Generate Auth
#laravel - 6 php artisan ui bootstrap --auth #laravel - 7 php artisan ui vue --auth
Now run npm command.
Install NPM
npm install
Run NPM
npm run dev
Add username column
Now add new column username to your users table.
#database/migrations/2020_10_12_000000_create_users_table.php <?php ... class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { ... $table->string('username')->nullable(); //added ... }); } ... }
Now migration username column:
php artisan migrate
Login Controller
#app/Http/Controllers/Auth/LoginController.php <?php ... use Illuminate\Http\Request;//added use Illuminate\Validation\ValidationException;//added public function username() { $identity = request()->get('identity'); // login with username or email $fieldName = filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; // login with username or name OR $fieldName = filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'name'; request()->merge([$fieldName => $identity]); return $fieldName; } protected function sendFailedLoginResponse(Request $request) { $request->session()->flash('login_error', trans('auth.failed')); throw ValidationException::withMessages( [ 'login_error' => [trans('auth.failed')], ] ); }
Login View
resources/views/auth/login.blade.php
#old code
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
#new code
<div class="form-group{{ $errors->has('identity') ? ' has-error' : '' }} row">
<label for="identity" class="col-md-4 control-label text-md-right">Email or Username</label>
<div class="col-md-6">
<input id="identity" type="identity" required class="form-control" name="identity"
value="{{ old('identity') }}" autofocus>
@if ($errors->has('identity'))
<span class="help-block">
<strong>{{ $errors->first('identity') }}</strong>
</span>
@endif
@if(session()->has('login_error'))
<p class="text-danger">{{ session()->get('login_error') }}</p>
@endif
</div>
</div>