Laravel

How to Login with Username or E-mail in Laravel

Adewale Ogundiran Charles
2 min readJan 20, 2020

--

By default you can login with E-mail on laravel if you are using the default laravel auth system, and i have been seeing a lot of people asking me how they can change this and start login in with Username or E-mail at ate same time.

Well here is a very simple and straightforward way to do that,

Open you Login controller and type in this code:

public function login(Request $request)

{

$input = $request->all();

$this->validate($request, [

‘username’ => ‘required’,

‘password’ => ‘required’,

]);

$fieldType = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? ‘email’ : ‘username’;

if (auth()->attempt(array($fieldType => $input[‘username’], ‘password’ => $input[‘password’]))) {

return redirect()->route(‘home’);

} else {

return redirect()->route(‘login’)

->with(‘error’, ‘Username/Email-Address And Password Are Wrong.’);

}

}

Now to go to login view and type this there:

@extends(‘layouts.app’)

@section(‘content’)

<div class=”container”>

<div class=”row justify-content-center”>

<div class=”col-md-8">

<div class=”card”>

<div class=”card-header”>{{ __(‘Login’) }}</div>

<div class=”card-body”>

<form method=”POST” action=”{{ route(‘login’) }}”>

@csrf

<div class=”form-group row”>

<label for=”username” class=”col-md-4 col-form-label text-md-right”>Username / E-mail</label>

<div class=”col-md-6">

<input id=”username” type=”username” class=”form-control @error(‘username’) is-invalid @enderror” name=”username” value=”{{ old(‘username’) }}” required autocomplete=”username” autofocus>

</div>

</div>

<div class=”form-group row”>

<label for=”password” class=”col-md-4 col-form-label text-md-right”>{{ __(‘Password’) }}</label>

<div class=”col-md-6">

<input id=”password” type=”password” class=”form-control @error(‘password’) is-invalid @enderror” name=”password” required autocomplete=”current-password”>

</div>

</div>

<div class=”form-group row”>

<div class=”col-md-6 offset-md-4">

<div class=”form-check”>

<input class=”form-check-input” type=”checkbox” name=”remember” id=”remember” {{ old(‘remember’) ? ‘checked’ : ‘’ }}>

<label class=”form-check-label” for=”remember”>

{{ __(‘Remember Me’) }}

</label>

</div>

</div>

</div>

<div class=”form-group row mb-0">

<div class=”col-md-8 offset-md-4">

<button type=”submit” class=”btn btn-primary”>

{{ __(‘Login’) }}

</button>

@if (Route::has(‘password.request’))

<a class=”btn btn-link” href=”{{ route(‘password.request’) }}”>

{{ __(‘Forgot Your Password?’) }}

</a>

@endif

</div>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

@endsection

I hope this can help you, don’t forget to drop your questions in the comment section below!

--

--

Adewale Ogundiran Charles

Full Stack Developer | Laravel(PHP) | Vue Js Developer | Frontend Developer | Backend Developer | WordPress Developer