CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Laravel   Laravel 5.7 Username Login and Registration Example Tutorial

Laravel 5.7 Username Login and Registration Example Tutorial

September 10, 2018 by SNK

Laravel 5.7 Login With Username and Email

In this laravel 5.7 login example we are going to see how to use username and email both for login and registration in laravel. We can either use username or email while logging inside laravel application.

We are going to follow step by step while going through this tutorial so, that it would be easy to follow me.

Let’s get started

What are we going to do ?

  1. Getting fresh project of laravel ready for this tutorial with default Auth scaffolding.
  2. Add username field in the migration and prepare database.
  3. Add username field in the fillable array, validation and create() method in User.php and RegisterController.php.
  4. Overriding default credentials method(); to accept username or email inside LoginController.php.

Whew, that’s looks plentiful. Believe me but its not. Lets get going

Step 1 : Getting Fresh Project Ready with Laravel Default Scaffolding.

I believe that you have fresh project of laravel ready.

Open command line terminal navigate to your project and type php artisan make:auth to make the login and registration form ready.

If you have noticed now, new files already have been created inside resources/views/

  1. home.blade.php
  2. auth/login.blade.php
  3. register.blade.php
  4. verify.blade.php
  5. passwords/email.blade.php
  6. passwords/reset.blade.php

This files are not new, if you are working with laravel already. But new version of laravel which is 5.7 now have verify.blade.php which is now used to confirm the email once the user is registered like most of the other websites. To use that feature you need to make some tweaks inside laravel code.

I am thinking of making separate tutorial for it. For now lets focus on what we are going to do in this tutorial.

Step 2 : Add Username Field in the Migration and Prepare Database

Now, its time to add username field in our database. Open the user migration file inside database/migrations/xxxx_xx_xx_xxxxxxx_create_users_table.php inside the laravel project directory and add the username field just below the name field in the migration file.

Make sure to add unique and make it nullable so that if users forget to type username they, can still login with the help of email.

PHP
1
$table->string('username')->nullable()->unique();

But, not to worry we can still validate and force user to push username for registration. Take a look at full code below.

Users Migration
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('username')->nullable()->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');
    }
}

After adding the username field. Go to command line and type php artisan migrate to create table and fields.

Make sure you have already configured your database inside the project .env files in your project root.

Step 3 : Adding Username Field to Fillable Array, Create Method and Validation Array

In this step we are going to add username field inside fillable array, create method array and validation array inside App/User.php.

Adding into fillable enables username field to be mass assignable.

Open RegisterController.php and search for protected function validator(array $data) and put the username inside it.

RegisterController Validator
PHP
1
2
3
4
5
6
7
8
9
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'username' => 'required|string|min:4',
]);
}

Finally, time to add username field in our register.blade.php template file. Just copy the email field and rename it as username in the necessary places like the code below.

register.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@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">{{ __('Register') }}</div>
 
                <div class="card-body">
                    <form method="POST" action="{{ route('register') }}">
                        @csrf
 
                        <div class="form-group row">
                            <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
 
                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
 
                                @if ($errors->has('name'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
 
                        <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 autofocus>
 
                                @if ($errors->has('username'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('username') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
 
                        <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{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
 
                                @if ($errors->has('email'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </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{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
 
                                @if ($errors->has('password'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
 
                        <div class="form-group row">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
 
                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                            </div>
                        </div>
 
                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Register') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

It seems that everything is finally in place. If you try to register, now you can use username to register inside the application. In the next step we are going to see how can we configure login to use both email and username.

Step 4 : Overriding Default Credentials method(); to Accept Username / Email Inside LoginController.php

In this step we are going to configure our login method in a such a way that, it can use both username and email to log in inside application.

Open LoginController.php and add this code just below the constructor.

LoginController.php
PHP
1
2
3
4
5
6
7
8
9
10
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? $this->username()
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}

This will override the laravel default credentials function / method and make use of both username and email. Final step is to make the changes inside the login.php and change the field of “email” which is currently set to input type email to text.

Finally hit php artisan serve from the command line terminal and login using username / email.

If you have any problem, mention them via comment or contact us through contact form in our website.

SHARE ON
Buffer

Enjoyed this article?

Like us on

Laravel laravel 5.7 login and registration tutorial laravel 5.7 login example laravel 5.7 login with username

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

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

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.