We're live-coding on Twitch! Join us!
How to create multi table authentication in laravel

How to create multi table authentication in laravel

Code Project

By default laravel authentication comes up with users table. Todays we are going to authenticate by teachers table rather than users table. Migrations and Creating teachers table let's start with create the migration file for our authentication table. Run the following command from terminal for create the migration file.

php artisan make:migration create_teacher_table  --create='teachers'

Now change the migration file's up method like the following.

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

From terminal now run the following command.

php artisan migrate

Teacher Model The Teacher model looks slightly different from traditional model. Take a look at the Teacher model.



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

class Teacher extends Authenticatable
{
    use Notifiable;

    protected $table = 'teachers';

    protected $fillable = ['email',  'password'];

    protected $hidden = ['password',  'remember_token'];


}

Make sure the model class(Teacher) must extends from Authenticatable class and use Notifiable trait class. Custom Guard setup Now open the config/auth.php file. By default laravel use "web" guard. We are going to add our custom guard "teacher".

  'guards' => [

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

        'teacher'  => [
          'driver'  => 'session',
          'provider' => 'teachers',
        ],

    ],


 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'teachers' => [
            'driver' => 'eloquent',
            'model'  => App\Teacher::class,
        ],
]

Now add some routes for teacher

Route::get('/teacher/login', 'Auth\TeacherLoginController@showLoginForm')->name('teacher.login');
Route::post('/teacher/login', 'Auth\TeacherLoginController@login')->name('teacher.login.post');
Route::post('/teacher/logout', 'Auth\TeacherLoginController@logout')->name('teacher.logout');

/_*
 _  teacher profile routes
 */
Route::group(['middleware'=>'teacher'], function() {
    Route::get('/teacher/home', 'Teacher\HomeController@index');
});

add a middleware to protect your routes

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfNotTeacher
{
    /_*
     _ Handle an incoming request.
     _
     _ @param  \Illuminate\Http\Request  $request
     _ @param  \Closure  $next
     _ @return mixed
     */
    public function handle($request, Closure $next, $guard="teacher")
    {
        if(!auth()->guard($guard)->check()) {
            return redirect(route('teacher.login'));
        }
        return $next($request);
    }
}

add the middleware class in your kernel.php file,

    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        // your custom middleware class 
        'teacher' => \App\Http\Middleware\RedirectIfNotTeacher::class,
    ];

In your teacher login from make sure you use teacher login route,

<form class="form-horizontal" method="POST" action="{{ route('teacher.login.post') }}">
    {{ csrf_field() }}

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

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

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

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

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

    <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
                </label>
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-8 col-md-offset-4">
            <button type="submit" class="btn btn-primary">
                Login
            </button>

        </div>
    </div>
</form>

TeacherLoginController Setup Now in our LoginController we need to specify which guard we want to use. We can do so by override the guard method.

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

class TeacherLoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = '/teacher/home';

    /**
     **_ Create a new controller instance.
     _**
     **_ @return void
     _**/
    public function __construct()
    {
      $this->middleware('guest')->except('logout');
    }
    /**
     _
     _ @return property guard use for login
     _
     _/
    public function guard()
    {
     return Auth::guard('teacher');
    }

    // login from for teacher
    public function showLoginForm()
    {
        return view('auth.teacher-login');
    }

 }