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

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

PHP TagsLaravel

Laravel Auth: Login with username instead of Email

Apr 9, 2019 Editorial Staff Leave a Comment

Share
Tweet
Share
17 Shares

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

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

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 15 views
  • Solution: windows photo viewer opens each time save a pic file 12 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • How to Create PDF File From HTML Form Using Fpdf? 9 views
  • All Countries SQL file with Country Codes to Download 8 views
  • How to create and download a Zip file with PHP 8 views
  • Simple PHP Shopping Cart 7 views
  • How to set up GitHub SSH in Ubuntu with example 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Laravel Eloquent Select Column as Alias 7 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 © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com