In this tutorial, I would like to share with you how to create Laravel 8 multiple authentications using middleware. we will create multi-auth in laravel using middleware. I will write step by step tutorial on creating multiple authentications in Laravel
first of all, we need to get fresh Laravel version application using bellow command, So open your terminal OR command prompt and run bellow
Via Composer Create-Project
command:
composer create-project laravel/laravel laravel-multi-login cd laravel-multi-login
create a database and let's open .env file and fill in all details like as bellow:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=here your DB name
DB_USERNAME=Your DB username
DB_PASSWORD=here your DB password
<?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->tinyInteger('status')->default('1');
$table->string('user_type',15)->default('User'); //Vendor//Admin//Subadmin
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
<?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','status','user_type','email_verified_at','password','remember_token' ]; /** * 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', ]; }
php artisan migrate
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev
In this step, we require to create admin middleware that will allow only admin access users to that routes. so let's create admin middleware routes. so let's create an admin user with the following steps.
php artisan make:middleware Admin
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class Admin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (Auth::check()) { if(Auth()->user()->user_type == 'Admin'){ return $next($request); } return redirect('home')->with('error',"You don't have admin access"); }else { return redirect('admin/login'); } } }
< .... protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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, ]; ....
Route::get('/admin', [App\Http\Controllers\Admin\DashboardController::class,'index'])->middleware(['admin']);
<?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'); } }
@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!') }} </div> </div> </div> </div> </div> @endsection
php artisan make:controller Admin/DashboardController
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; class DashboardController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('admin.dashboard'); } }
@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 are Admin.
</div>
</div>
</div>
</div>
</div>
@endsection
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Auth; 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 */ public function redirectTo(){ $role = Auth::user()->user_type; // Check user role switch ($role) { case 'Admin': return '/admin'; break; case 'User': return RouteServiceProvider::HOME; break; default: return RouteServiceProvider::HOME; break; } } /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } }
php artisan make:seeder CreateUsersSeeder
<?php use Illuminate\Database\Seeder; use App\User; class CreateUsersSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $user = [ [ 'name'=>'Admin', 'email'=>'admin@trickprof.com', 'user_type'=>'Admin', 'password'=> bcrypt('12345678'), ], [ 'name'=>'User', 'email'=>'user@trickprof.com', 'user_type'=>'User', 'password'=> bcrypt('12345678'), ], ]; foreach ($user as $key => $value) { User::create($value); } } }
Composer dump-autoload
php artisan db:seed --class=CreateUsersSeeder
php artisan serve
We are Recommending you:
- How to change timezone in laravel 8
- Laravel Command List
- Laravel's .htaccess to remove "public" from URL
- Integrate Zoho SMTP Mail Configurations in Laravel?
- Laravel 7 multi auth login
- How to create real time sitemap.xml file in Laravel
- How to use soft delete in Laravel?
- How to generate dynamic real time sitemap.xml file in Laravel 8
- Laravel 8 .htaccess file for php 8
Step Out of Your Comfort Zone: 10 Powerful...
Is Mobile Reels Harming Our Children? Here's...
Simple body language tricks1. Stand with...
Best Free Websites to Learn CodingIf you...
The 7 Habits of Highly Effective...
#...
A class is an Object. We also name objects...
In this tutorial, I would like to share with...
Following steps that help you to customize...