Laravel 7|8 Multi Auth: Create Multiple Authentication in Laravel

Last updated on by Digamber
Eventually, we are going to learn how to create multiple auth (Authentication) in Laravel 7 using middleware, and we will also consider other laravel imperatives that are useful to build laravel basic auth app from starting.

Multi Authentication in laravel is not a tough task to be done. In this tutorial, we will go through every step that will help us in building multi auth system with ease.

If you want to develop strong knowledge about Token-Based Authentication, then must check out: Laravel JWT authentication tutorial.

Laravel 7 Multiple Authentication Example

What Multiple auth system refers to? Well, as the name suggests, it is a terminology that refers to the process of login by multiple users based on roles in an application.

In general, Authentication is the security process, and it indicates acknowledging the genuine user with proper account details.

Here is the archetype of this tutorial, we will develop two users one is admin, and the other one is a regular user. Based on their roles, we will allow them to access in the app using middleware. Let us begin our work and start building our application.

Download Laravel Application

We will follow the order of precedence and download the new laravel application using the following command.

composer create-project laravel/laravel laravel-multi-auth --prefer-dist

Now, we have conjugated all the files, get inside the project directory.

cd laravel-multi-auth

Configure Database Connection

Establish a database connection, open .env file and define your database details it makes the consensus between laravel and database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

We are using MAMP open-source tool to make manage laravel multi auth (authentication). The following error may occur and create ruckus while running database migration.

SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel_db and table_name = migrations and table_type = ‘BASE TABLE’)

Place the following code below the database configuration in your .env file.

DB_HOST=localhost;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock

Set Up Model and Run Migration

We have to declare the new property, name it (‘is_admin’), and propel it into users’ table by running the migration.

Incorporate the following code inside database/migrations/timestamp_create_users_table.php file.

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Now, get inside the app/User.php file and add the newly created is_admin property.

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

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

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

We are all set with everything and good to go with the migration, run the below command to migrate.

php artisan migrate

Generate Auth Scaffolding

You won’t have to put intense efforts to create the authentication UI in laravel from testing purposes. Developers can give precedence to other work and leave the auth UI part on laravel’s discretion.

We can originate the auth scaffold using a simple command. It consists of login, register, and dashboard UI.

Install Laravel 7 UI package

composer require laravel/ui

Now using the below command create the auth archetypes.

php artisan ui bootstrap --auth

Run following command to compile your fresh scaffolding.

npm install && npm run dev

Set Up Admin Middleware

Theoretically, this is a foundation step of laravel multi auth system tutorial. We are willing to cover how to allow only those users who belong to the admin category with a specific route.

To complete the imperatives, evoke the below command from your terminal window.

php artisan make:middleware Admin

Open app/Http/middleware/IsAdmin.php and paste the following code.

<?php

namespace App\Http\Middleware;

use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
   
        return redirect('home')->with('error',"Only admin can access!");
    }
}

You have to define the Admin middleware in app/Http/Kernel.php file, so paste the following code inside of $routeMiddleware array.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

    'admin' => \App\Http\Middleware\Admin::class,
];

Set Up Route

In this step, we will create a single route for admin and bind it with the home page, and ultimately it will allow us to access the laravel page. Paste the following code in routes/web.php file.

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::get('admin/home', 'HomeController@handleAdmin')->name('admin.route')->middleware('admin');

Configure Home Controller

We have to incorporate the handleAdmin() method inside the HomeController class, open app/Http/Controllers/HomeController.php, and add the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function handleAdmin()
    {
        return view('handleAdmin');
    }    
}

Configure Blade View

In this step we have to create a new blade template for handling authentication based on auth state.

Open the pre-defined resources/views/home.blade.php file and insert the foundation code inside the file.

@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">Dashboard</div>

                <div class="card-body">
                    You don't seem to be an admin!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Create and open resources/views/handleAdmin.blade.php file and add the code.

@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">Dashboard</div>

                <div class="card-body">
                    Hey! you are admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Configure Login Controller

In this step we will configure LoginController class, define the login() method and insert the following code. It handles the server-side validation, redirects to admin dashboard if the logged in user is admin.

Incorporate the following code in app/Http/Controllers/Auth/LoginController.php file

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

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 = '/admin/route';

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

    public function login(Request $request)
    {  
        $inputVal = $request->all();
   
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
   
        if(auth()->attempt(array('email' => $inputVal['email'], 'password' => $inputVal['password']))){
            if (auth()->user()->is_admin == 1) {
                return redirect()->route('admin.route');
            }else{
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email & Password are incorrect.');
        }     
    }
}

Seed Database with User Data

Theoretically, we need to set a few users with is_admin values 1 and 0 simultaneously. So, we will use the laravel’s default database seeder mechanism to seed the database. Execute the following class to create the DummyUsersSeeder file.

php artisan make:seeder DummyUsersSeeder

Head over to database/seeds/DummyUsersSeeder.php file and insert the following data.

<?php

use Illuminate\Database\Seeder;
use App\User;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $userData = [
            [
               'name'=>'Admin',
               'email'=>'johndoe@hotmail.com',
                'is_admin'=>'1',
               'password'=> bcrypt('07070707'),
            ],
            [
               'name'=>'Regular User',
               'email'=>'reguser@gmail.com',
                'is_admin'=>'0',
               'password'=> bcrypt('07070707'),
            ],
        ];
  
        foreach ($userData as $key => $val) {
            User::create($val);
        }
    }
    
}

Run & Test The Laravel Multi Auth App

Evoke the laravel multi auth application with the given below command.

php artisan serve

Open the following URL on your browser on: http://127.0.0.1:8000/login

Test The Non Admin Account
Ultimately, you have to enter the following credentials to check a non-admin account.

Email Address:  reguser@gmail.com
Password:       07070707

Laravel 7 Multi Auth App

Test The Admin Account
Finally, you have to provide the following details to check an admin account.

Email Address:  johndoe@hotmail.com
Password:       07070707

Multi Auth in Laravel 7

The Bottom Line

Ultimately, we have completed the laravel 7 Multi authentication tutorial. We have developed a simple auth app in which we followed the order of precedence with discretion to achieve the desired functionality. In the entire multi auth memoir, we tried to shed light on the foundational topics with persistence. Eventually, we learned how to stop non-admin users from accessing admin account using laravel authentication middleware.

Generically, this is just a beginning with to elevate your laravel development skills. You can add various features to protect the admin account.

If you found any act of recklessness by me, then do let me know. It must have been done unknowingly, and i will fix it. Lastly, you can find the entire code of this tutorial on GitHub.

I hope you liked this tutorial, and you can be grateful to me or my intense efforts that i have put in this tutorial by sharing this tutorial with others. So, don’t forget to share it with others, have a good day.