Changing Authentication Table in Laravel

Changing Authentication Table in Laravel

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 !!

Web Stuff Enthusiast.

Related Posts

16 comments On Changing Authentication Table in Laravel

  • Sorry I am new in Laravel, could u help me. I got problem. Why my data couldn’t save in database?

  • Great post. Thanks!
    After changing user table to “members”, why I still need to get authenticated user by Auth::user()?
    How can I get autheticated user by Auth::member()?
    Thanks,

    • Auth::user is the default method provided by Laravel for authentication. Why would you want to change that?

  • Nicolae Florescu

    What if the email is stored in a different table and referenced by email_id?
    I am in this problem now and I found that i can use into the User model a method
    public function findForPassport($identifier)
    {
    return Email::where(’email’, $identifier)->first();
    }

    but now I get a different error
    Call to undefined method Illuminate\\Database\\Query\\Builder::getAuthPassword().
    The passpord is into the Users table ans passport should find it, but it doesn’t happening
    Anybody knows why?
    Using
    public function getAuthPassword() {
    return $this->password();
    }
    in Users model does not help
    Thanks

  • Can I login with the current table in database that have been registered by admin?

  • This is wrong. We should actually keep existing users table and create a new table customers (depends on requirement) and override Auth::attempt accordingly.

  • Hey, I got an error after integrate this, the error is as follows

    Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must be an instance of Illuminate\Contracts\Auth\UserProvider, null given, called in vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 123

    Please let me know if there has an fixes

  • Greate Tutorial!! Thank you..

  • Great tutorial! Does this works also in case we need to have two different authentication tables? (i.e. one for backend users – admin, writers, ectc., maybe with different roles and permissions privileges – and one for frontend users – customers, etc.)

  • same ploblem. need some one help

  • I made all the changes as above but “Auth::attempt() method is still returning false when I have the matching email and password in my custom talbe. It is atleast not throwing any error.

Leave a reply:

Your email address will not be published.

Site Footer