Skip to content
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos

Home » Laravel » Laravel 8 Multiple Authentication Example Tutorial

Laravel 8 Multiple Authentication Example Tutorial

Laravel 8 Multiple Authentication Example Tutorial

Posted on October 7, 2020September 26, 2021 By XpertPhp No Comments on Laravel 8 Multiple Authentication Example Tutorial

Today, we are going to how to create multiple authentications using the laravel 8 (Laravel 8 Multiple Authentication Example).

Overview

Step 1: Install Laravel

Step 2: Setting Database Configuration

Step 3: Create Table using migration

Step 4: Install the Laravel/UI package

Step 5: Install the Laravel Auth command

Step 6: Create IsAdmin Middleware

Step 7: Modify the Controllers and Model

Step 8: Define The Route

Step 9: Create Blade Files

Step 10: Run Our Laravel Application

Step 1: Install Laravel

We are going to install laravel 8, so first open the command prompt or terminal and go to xampp htdocs folder directory using the command prompt. after then run the below command.

1
composer create-project --prefer-dist laravel/laravel laravel8_multiple_authentication

Step 2: Setting Database Configuration

After the complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel8_multiple_authentication)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Create Table using migration

Now, We need to update the user’s migration tables. so we will update the user’s migration table, see the below file to update the code for the users table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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->id();
            $table->string('name');
            $table->string('email')->unique();
            $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');
    }
}
?>

Run the below command. after the changes above file.

1
php artisan migrate

Step 4: Install the Laravel/UI package

We need to laravel UI package so we will install the package using the below command.

1
composer require laravel/ui

when completed successfully installation of laravel UI package then we will see look like as below type of output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Using version ^2.0 for laravel/ui
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing laravel/ui (v2.0.1): Downloading (100%)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.

Step 5: Install the Laravel Auth command

Now, we will install the laravel authentication using the below command.

1
php artisan ui bootstrap --auth

here, Laravel extracted into a scaffolding separate laravel UI packages.

1
2
3
Bootstrap scaffolding installed successfully.
Please run "npm install && npm run dev" to compile your fresh scaffolding.
Authentication scaffolding generated successfully.

Step 6: Create Middleware

Now, we will create IsAdmin Middleware using the below command and we need some changes in handle method. so you can see the below code.

1
php artisan make:middleware IsAdmin

app/Http/Middleware/IsAdmin.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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.");
    }
}
?>

After complete changes. we need to assign route on middleware array in the app/Http/Kernel.php file. so you can see the below code.

app/Http/Kernel.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var 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,
'is_admin' => \App\Http\Middleware\IsAdmin::class,
    ];

Step 7: Modify the controller and model

Now here, we need to add the adminHome() method in the HomeController.php file.

app/Http/Controllers/HomeController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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 for admin.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
}
?>

And second, we need to update the LoginController.php file. so you can follow the below code.

app/Http/Controllers/Auth/LoginController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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 = RouteServiceProvider::HOME;
 
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
public function login(Request $request)
    {  
        $input = $request->all();
  
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
  
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->is_admin == 1) {
                return redirect()->route('admin.home');
            }else{
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }
          
    }
}
?>

app/User.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
 
namespace App/Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
 
class User extends Authenticatable
{
    use HasFactory;
    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',
    ];
}
?>

Step 8: Define The Route

We will open the web.php in the routes directory and paste below the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
use App\Http\Controllers\HomeController;
 
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::get('/', function () {
    return view('welcome');
});
 
Auth::routes();
 
Route::get('/home',[HomeController::class, 'index'])->name('home');
Route::get('admin/home',[HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');
?>

Step 9: Create Blade Files

here in this step, we need to create a new adminHome.blade.php file or you can copy the file of home.blade.php and change the file name to the adminHome.blade.php.

adminHome.blade.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@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 (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
 
                    You are logged in admin dashboard!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 10: Run Our Laravel Application
We can start the server and run this example using the below command.

1
php artisan serve

Now we will run our example using the below Url in the browser.

1
http://127.0.0.1:8000/

Download

Please follow and like us:
error
fb-share-icon
Tweet
fb-share-icon

Recommended Posts:

  • laravel eloquent Distinct Count query example
  • Laravel 6 pdf generator tutorial using dompdf
  • laravel eloquent insert query example
  • Laravel 8 Instamojo Payment Gateway Integration Example Tutorial
  • laravel eloquent delete query example
Laravel Tags:Laravel 8, laravel 8 example, laravel 8 tutorial

Post navigation

Previous Post: Laravel 8 Newsletter Tutorial With Example
Next Post: angular 10 image upload with preview image example

Latest Posts

  • Laravel Check If Foreach is Empty Example
  • Laravel Check Array Empty in Blade
  • PHP Datatables CRUD Example
  • How to Convert Date and Time from one timezone to another in php
  • how to get current date and time in php
  • Drag and Drop Reorder Items with jQuery, PHP & MySQL
  • Laravel 9 Toastr Notifications Example Tutorial
  • Laravel 9 CRUD Operation Example Using Google Firebase
  • Laravel 9 CKeditor Image Upload With Example
  • Laravel 9 Summernote Image Upload With Example

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tricks jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch Laravel Socialite laravel social login nodejs pagination payment gateway php with mysql react js tutorial rewrite rule send mail validation wysiwyg editor

Copyright © 2018 - 2022,

All Rights Reserved Powered by XpertPhp.com