This tutorial will guide you how to go about Changing Authentication Table in Laravel to use table other than default table users.

This steps are given as per the Laravel v 5.5

Before Going into the Steps, Make sure you have following ready.

Step 1 : Create and Run Migrations.

You need to create and run the migrations for your new table. By running the following commands.

php artisan make:migration create_customusers_table

This will create a new migration script under folder database > migrations. You can modify the file to include more columns in your table as per the requirements. As an example I have modified my script to include the following fields (name, username, passcode, email, active, remember_token)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomusersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customusers', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('username');
          $table->string('passcode');
          $table->string('email');
          $table->boolean('active');
          $table->rememberToken();
          $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customusers');
    }
}

After you have done the modifications , you can run the migrate command to create the table in your database.

php artisan migrate

php artisan migrate customuser table

Note : You can skip this step if you already have the table created with desired username and password fields.


Step 2: Create Model for your table

 

Since now we have the table ready that we want to use for the authentication, Let's create a Model against it.

I created a file CustomerUser.php under App folder which extends the Illuminate\Foundation\Auth\User class.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class CustomUser extends Authenticatable
{
    use Notifiable;

    protected $table = 'customusers';

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'passcode', 'remember_token',
    ];


    public function getAuthPassword()
    {
      return $this->passcode;
    }
}

Since I am using a different field passcode for storing the passwords. I have overridden the getAuthPassword() method for that, you can skip this if your field name for storing password is password.


Step 3: Modify auth.php file

Next we need to modify our provider and passwords array inside config > auth.php file.

Providers is how laravel authentication system get's the user data form the database, since the default setting to authenticate against users table, we need to add the provider for customusers table.

Add following entry to the providers object.

'customusers' => [
            'driver' => 'eloquent',
            'model' => App\CustomUser::class,
        ],

Also add following entry to passwords object

        'customusers' => [
            'provider' => 'customusers',
            'table' => 'password_resets',
            'expire' => 60,
        ],

Next we need to modify the guards to use the customusers provider instead of default users provider. Modify the following entry under guards object.

'web' => [
            'driver' => 'session',
            'provider' => 'customusers',
        ],

Also modify the defaults option to update the passwords

'defaults' => [
        'guard' => 'web',
        'passwords' => 'customusers',
    ],

Step 4: Modify Authentication Controllers and views.

We need to modify the RegisterController file to modify the fields as per our new table.

<?php

namespace App\Http\Controllers\Auth;

use App\CustomUser;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{


    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

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

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:customusers',
            'email' => 'required|string|email|max:255|unique:customusers',
            'passcode' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return Customuser::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'passcode' => bcrypt($data['passcode']),
            'active' => 1,
        ]);
    }
}

Also modify the register.blade.php view file to accommodate for your new table fields.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Register</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('register') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>



                        <div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Username</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="username" value="{{ old('username') }}" required autofocus>

                                @if ($errors->has('username'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('username') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('passcode') ? ' has-error' : '' }}">
                            <label for="passcode" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="passcode" type="password" class="form-control" name="passcode" required>

                                @if ($errors->has('passcode'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('passcode') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="passcode-confirm" class="col-md-4 control-label">Confirm Password</label>

                            <div class="col-md-6">
                                <input id="passcode-confirm" type="password" class="form-control" name="passcode_confirmation" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

That's All is required in Changing Authentication Table in Laravel !!

Comments