• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
logo

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Write For US
  • News
  • About Us
  • Snippets
You are here: Home / PHP / Laravel Auth: Login with username instead of Email

Laravel Auth: Login with username instead of Email

Apr 9, 2019 by Editorial Staff Leave a Comment

Setup Project

laravel new viauser

Update the .env file with your desired database details.

Run the following command to create the scaffold for authentication pages.

php artisan make:auth

Next, we want to add our new field, username to our database migration structure.

Open this file database/migrations/create_users_table.php. Add the username field in the up() function after the name field.

So the final function will look like below.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Now migrate the database by using the following command.

php artisan migrate

Registering New User

We need to add username field to our registration form,  to save username for a user. Go to file resources/views/auth/register.blade.php

Add the following code after the name row to display the username 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>

Registration controller

Now let’s focus on the register controller part, this is where the backend action starts.

Go to the file RegisterController.php in app/Http/Controllers/Auth directory. Find the validator method and add the username line after name validation entry. It should have unique entry validation too.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'username' => 'required|string|max:255|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

The validation goes like this, username should be a string, not more than 255 characters, and unique value.

Let’s move to the create function in the same file. Add the username field after name field in the eloquent query.

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        ]);
}

Now we have added the username in the fillable field in the User model. Otherwise, even if you fill the username in the form, it will save as blank. Not yet encountered with fillable, please read this article.

class User extends Authenticatable
{
    use Notifiable;

    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

Now we have done with the registration part. Let’s start the login part of our application.

Log in with username or email

First, we will add the username field to login view.

Go to this file resources/views/auth/login.blade.php

And update the email field to username field.

<div class="form-group row">
    <label for="email" 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 autofocus>

        @if ($errors->has('username'))
        <span class="invalid-feedback" role="alert">
            <strong>{{ $errors->first('username') }}</strong>
        </span>
        @endif
    </div>
</div>

Login Controller

Let’s move to the final bit of code, the LoginController.php

Add a protected field username, in order to change the validation field to the username. We will add the username method to return the fieldType. Rest other things Laravel auth lib will take care.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

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';


    protected $username;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        $this->username = 'username';
    }

    /**
     * Get username property.
     *
     * @return string
     */
    public function username()
    {
        return $this->username;
    }
}

That’s it!. I hope you have learned a new thing. Please feel free to contact me at contact us page in case of any doubts.


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Filed Under: PHP Tagged With: Laravel

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar




Quick Links

  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Base64 Decode Online
  • Base64 Encode Online

Subscribe

* indicates required

Share

   

Hot topics

  • A Simple YouTube Video Downloader Script in PHP 269 views
  • Replace “\n” with new line characters, using Notepad++ 242 views
  • Add FTP/SFTP in Visual Studio Code 176 views
  • Open a URL in a new tab using JavaScript 140 views
  • Using Third-Party Libraries in Codeigniter 139 views
  • Upload Multiple Images and Store in Database using PHP and MySQL. 130 views
  • Laravel Image Intervention Tutorial With Example 125 views
  • Hierarchical Tree view Category Example in Laravel 112 views
  • Spout, an awesome library for reading and writing in Excel. 102 views
  • Manually Install APK Files In Android Studio Emulator 98 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube

Copyright © 2021 · TutsPlanet Gene Theme on Genesis Framework · Powered By BunnyCDN