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
Laravel 6 Multiple Authentication

Laravel 6 Multiple Authentication Example Tutorial

Posted on September 22, 2019September 26, 2021 By XpertPhp 1 Comment on Laravel 6 Multiple Authentication Example Tutorial

Today, we are going to how to create multiple authentications using the laravel 6 (like front-end login and register and back-end login and register).

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 1: Install Laravel

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

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

Step 2: Setting Database Configuration

After 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(larave6_multi_auth)
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 users migration table. so we will update the users migration table, see below file in update the code for 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->bigIncrements('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
./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 (v1.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: 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 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 below command and we need to some changes in handle method. so you can see 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 routeMiddleware array in app/Http/Kernel.php file. so you can see 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 adminHome() method in 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 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
<?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',
    ];
}
?>

Step 8: Define The Route

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
 
/*
|--------------------------------------------------------------------------
| 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', '[email protected]')->name('home');
Route::get('admin/home', '[email protected]')->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 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

Download

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

Recommended Posts:

  • Laravel 7 s3 File Upload Tutorial With Example
  • Laravel one to one eloquent relationship tutorial example
  • codeigniter select query with multiple clauses
  • Laravel One To One Polymorphic Eloquent Relationship Tutorial Example
  • Laravel 7 integrate summernote with example
Laravel, MySql Tags:laravel 6, Laravel 6 Eloquent, Laravel 6 Routing, Laravel 6 User Authentication, multiple authentication

Post navigation

Previous Post: Laravel 6 UI Package with Authentication Tutorial
Next Post: CodeIgniter Upload Image File with preview using Jquery Ajax

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

Latest Posts

  • 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
  • Laravel 9 Stripe Payment Gateway Integrate Example
  • How To Send Email Using Mailtrap In Laravel 9
  • Laravel 9 Fullcalendar Ajax Example Tutorial

Tools

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

Copyright © 2018 - 2022,

All Rights Reserved Powered by XpertPhp.com