Laravel 10 Multiple Authentication Tutorial

Introduction

Laravel is a powerful and popular open-source PHP framework. It is used to develop web applications quickly and easily. One of the most important features of Laravel is its authentication system. It provides a simple and secure way to authenticate users.

In this tutorial, we will learn how to implement multiple authentication in Laravel 10. We will create two different authentication systems for two different user types. We will also learn how to protect routes and resources based on the user type.

Prerequisites

Before starting this tutorial, you should have a basic understanding of the following:

• PHP
• HTML
• CSS
• Laravel

Step 1: Create a New Laravel Project

First, we need to create a new Laravel project. To do this, open the terminal and run the following command:

composer create-project –prefer-dist laravel/laravel laravel-10-multiple-auth

This command will create a new Laravel project in the laravel-10-multiple-auth directory.

Step 2: Create the Database

Next, we need to create a database for our project. To do this, open the .env file and update the following lines with your database credentials:

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

Once you have updated the database credentials, run the following command to create the database:

php artisan migrate

Step 3: Create the User Model

Now, we need to create the user model. To do this, run the following command:

php artisan make:model User -m

This command will create a new User model in the app directory.

Step 4: Create the User Migration

Next, we need to create the user migration. To do this, open the database/migrations/create_users_table.php file and update it with the following code:

public function up()
{
Schema::create(‘users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(’email’)->unique();
$table->string(‘password’);
$table->string(‘type’)->default(‘user’);
$table->rememberToken();
$table->timestamps();
});
}

This code will create a users table with the necessary fields.

Step 5: Create the User Factory

Next, we need to create the user factory. To do this, open the database/factories/UserFactory.php file and update it with the following code:

$factory->define(User::class, function (Faker $faker) {
return [
‘name’ => $faker->name,
’email’ => $faker->unique()->safeEmail,
‘password’ => bcrypt(‘password’),
‘type’ => ‘user’,
];
});

This code will generate dummy data for the users table.

Step 6: Create the Authentication Controllers

Now, we need to create the authentication controllers. To do this, run the following command:

php artisan make:controller Auth/AdminAuthController
php artisan make:controller Auth/UserAuthController

This command will create two new authentication controllers in the app/Http/Controllers/Auth directory.

Step 7: Create the Authentication Views

Next, we need to create the authentication views. To do this, create two new directories in the resources/views directory: admin and user. Then, create the following files in each directory:

• login.blade.php
• register.blade.php
• reset.blade.php
• verify.blade.php

Step 8: Create the Authentication Routes

Now, we need to create the authentication routes. To do this, open the routes/web.php file and update it with the following code:

// Admin Authentication Routes
Route::prefix(‘admin’)->group(function () {
Route::get(‘login’, ‘Auth\AdminAuthController@showLoginForm’)->name(‘admin.login’);
Route::post(‘login’, ‘Auth\AdminAuthController@login’);
Route::post(‘logout’, ‘Auth\AdminAuthController@logout’)->name(‘admin.logout’);
Route::get(‘register’, ‘Auth\AdminAuthController@showRegistrationForm’)->name(‘admin.register’);
Route::post(‘register’, ‘Auth\AdminAuthController@register’);
Route::post(‘password/email’, ‘Auth\AdminAuthController@sendPasswordResetLink’)->name(‘admin.password.email’);
Route::get(‘password/reset’, ‘Auth\AdminAuthController@showLinkRequestForm’)->name(‘admin.password.request’);
Route::post(‘password/reset’, ‘Auth\AdminAuthController@reset’);
Route::get(‘password/reset/{token}’, ‘Auth\AdminAuthController@showResetForm’)->name(‘admin.password.reset’);
});

// User Authentication Routes
Route::prefix(‘user’)->group(function () {
Route::get(‘login’, ‘Auth\UserAuthController@showLoginForm’)->name(‘user.login’);
Route::post(‘login’, ‘Auth\UserAuthController@login’);
Route::post(‘logout’, ‘Auth\UserAuthController@logout’)->name(‘user.logout’);
Route::get(‘register’, ‘Auth\UserAuthController@showRegistrationForm’)->name(‘user.register’);
Route::post(‘register’, ‘Auth\UserAuthController@register’);
Route::post(‘password/email’, ‘Auth\UserAuthController@sendPasswordResetLink’)->name(‘user.password.email’);
Route::get(‘password/reset’, ‘Auth\UserAuthController@showLinkRequestForm’)->name(‘user.password.request’);
Route::post(‘password/reset’, ‘Auth\UserAuthController@reset’);
Route::get(‘password/reset/{token}’, ‘Auth\UserAuthController@showResetForm’)->name(‘user.password.reset’);
});

This code will create the necessary routes for both the admin and user authentication systems.

Step 9: Create the Authentication Guards

Next, we need to create the authentication guards. To do this, open the config/auth.php file and update it with the following code:

‘guards’ => [
‘admin’ => [
‘driver’ => ‘session’,
‘provider’ => ‘admins’,
],
‘user’ => [
‘driver’ => ‘session’,
‘provider’ => ‘users’,
],
],

This code will create two authentication guards for the admin and user authentication systems.

Step 10: Create the Authentication Providers

Finally, we need to create the authentication providers. To do this, open the config/auth.php file and update it with the following code:

‘providers’ => [
‘admins’ => [
‘driver’ => ‘eloquent’,
‘model’ => App\Admin::class,
],
‘users’ => [
‘driver’ => ‘eloquent’,
‘model’ => App\User::class,
],
],

This code will create two authentication providers for the admin and user authentication systems.

Conclusion

In this tutorial, we have learned how to implement multiple authentication in Laravel 10. We have created two different authentication systems for two different user types. We have also learned how to protect routes and resources based on the user type.
[ad_1]

In some cases, you may need to implement multiple authentication systems within a single Laravel application to cater to different user types or roles. This could be useful for scenarios like admin panels, user dashboards, or API authentication.

Laravel 10 multi (auth) authentication example tutorial. In this guide, you will learn how to create multiple auth system in Laravel 10 based on specific roles like admin, user, etc.

Laravel 10 Multiple Authentication Tutorial

  • Step 1: Setting up a New Laravel Project
  • Step 2: Connecting App to the Database
  • Step 3: Setting up migration and model
  • Step 4: Create Middleware and Setting up
  • Step 5: Define Route
  • Step 6: Create Methods in Controller
  • Step 7: Create Blade View
  • Step 8: Start Development Server

Step 1: Setting up a New Laravel Project

First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:

composer create-project --prefer-dist laravel/laravel LaraMulti

Step 2: Connecting App to the Database

Once you have successfully downloaded laravel app in your system. Then you need to visit your project root directory and find .env file. Andset up database credentials:

  DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3: Setting up migration and model

Next, add is_admin column in the users table using mirgration file. So, Open the creates_users_table.php migration file, which is placed on Database/migration and update the following field for admin.

$table->boolean('is_admin')->nullable();

Next open app/User.php and update the below field name is_admin here:

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
  
class User extends Authenticatable
{
    use HasFactory, 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',
    ];
}

Now, add is_admin filed after that will use the below command for creating this field into the database.

php artisan migrate

Now, create a build-in authentication system. Use the below command for creating the default auth system in laravel. And change laravel build-in auth system to multi auth system

This command will create routes, controllers and views files for Laravel Login Authentication and registration. It means to provide a basic laravel login authentication and registration Complete system. Let’s open the command prompt and type the below command.

Then install Laravel 10 UI in your project using the below command:

 composer require laravel/ui 
composer laravel ui

Now, execute the below command on terminal for creating login, registration, forget password and reset password blade files:

  php artisan ui bootstrap --auth 

Then execute the following commands:

npm install
npm run dev

Step 4: Create Middleware and Setting up

In this laravel multi auth system, create a middleware for checking the users. Who can access the admin area or who can access the normal user area.

php artisan make:middleware IsAdmin

After creating a middleware go-to app/Http/middleware. Implement the logic here for checking a logged in users. Update the code in this handle function.

<?php
  
namespace App\Http\Middleware;
  
use Closure;
   
class IsAdmin
{
    /**
     * 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’,"You don't have admin access.");
    }
}

Then register this middleware in the app/Http/Kernel.php. So, open kernal.php and add the following $routeMiddleware property in it:

....
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,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'is_admin' => \App\Http\Middleware\IsAdmin::class,
];
....

Step 5: Define Route

Create routes and add it on web.php file as like below.

Open routes/web.php file

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\HomeController;

Route::get('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');

Step 6: Create Methods in Controller

Now open the HomeController.php file, which is placed on app/Http/Controllers/ directory. Then add the following code into it:

<?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');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
    
}

Step 7: Create Blade View

Now, create two blade view files first is display home page and second is display after login.

Open the resources/views/home.blade. file and update the below 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">
                    @if(auth()->user()->is_admin == 1)
                    <a href="{{url('admin/routes')}}">Admin</a>
                    @else
                    <div class=”panel-heading”>Normal User</div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, I checked the user profile. If it is admin, it will navigate to the admin area. Otherwise, it will redirect to users area.

Create admin.blade.php file inside resources/views/ directory and update the following 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">
                    @if(auth()->user()->is_admin == 1)
                    <a href="{{url('admin/routes')}}">Admin</a>
                    @else
                    <div class=”panel-heading”>Normal User</div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 8: Run development server

Now, start the development server using the below command and test our Laravel 10 multi auth system:

php artisan serve

After complete all steps, see the last testing steps for laravel multi auth system :

  • First, register a user through the Laravel register.
  • Second Change the status is_admin = 1 in users table
  • Third Login into a laravel application

Recommended Laravel Posts

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00