Laravel 7 multi auth login

Laravel 7 multi auth login

In this tutorial, i would like to share with you how to create laravel  multiple authentication using middleware. we will create multi auth in laravel  using middleware. i will write step by step tutorial of creating multiple authentication in laravel

Step 1: Install 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 --prefer-dist laravel/laravel blog

Step 2: Database Configuration
let's open .env file and fill all details like as bellow:
File Path :-> .env
 
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

Step 3: Update Migration
File Path :-> database/migrations/2014_10_12_000000_create_users_table.php
<?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->string('password');
            $table->string('user_type',10)->default('User'); //Admin
            $table->tinyInteger('status')->default('1');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Step 4: Update Model
File Path :-> app/User.php
<?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','user_type','status'
    ];

    /**
     * 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 we need to run migration.
so let's run bellow command:
php artisan migrate

Step 5: Create Auth using scaffold
Now, in this step, we will create auth scaffold command to create login, register and dashboard. so run following commands:
Laravel  UI Package
composer require laravel/ui 
Generate auth
php artisan ui bootstrap --auth 
npm install
npm run dev

Step 6: Create Admin Middleware
In this step, we require to create admin middleware that will allows only admin access users to that routes. so let's create admin middleware 
routes. so let's create admin user with following steps.
php artisan make:middleware Admin
file path: -> app/Http/middleware/Admin.php
<?php
  
namespace App\Http\Middleware;
use Illuminate\Http\Request; 
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()->check() && auth()->user()->user_type == "Admin"){
            return $next($request);
        }
   
        return redirect('admin/login')->with('error',"You don't have admin access.");
    }
}
file path : -> app/Http/Kernel.php
<
....
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,
    ];
....


Step 7: Create Admin Route
Here, we need to add one more route for admin user home page so let's add that route in web.php file.
file path : -> routes/web.php
Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('admin');


Step 8: Add Method on Controller
Here, we need add adminHome() method for admin route in HomeController. so let's add like as bellow:
file path : ->app/Http/Controllers/HomeController.php
<?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 9: Create Blade file
In this step, we need to create new blade file for admin and update for user blade file. so let's change it.
file path : ->  resources/views/home.blade.php
@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 normal user.
                </div>
            </div>
        </div>
    </div>
</div>

@endsection 
file path : ->  resources/views/adminHome.blade.php
@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

Step 10: Update on LoginController
In this step, we will change on LoginController, when user will login than we redirect according to user access. if normal user than we will redirect to home route and if admin user than we redirect to admin route. so let's change.
file path : ->  app/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; 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 */ 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()->user_type == 'Admin') { return redirect('admin'); }else{ return redirect()->route('home'); } }else{ return redirect()->route('login') ->with('error','Email-Address And Password Are Wrong.'); } } public function logout(Request $request) { if(isset(Auth::user()->user_type)){ $role = Auth::user()->user_type; }else { $role = ''; } Auth::logout(); // Check user role switch ($role) { case 'Admin': return redirect('/admin/login'); break; case 'User': return redirect('/'); break; default: return redirect('/home'); break; } } }


Step 11: Create Seeder
We will create seeder for create new admin and normal user. so let's create seeder using following command:
php artisan make:seeder CreateUsersSeeder
file path : -> database/seeds/CreateUsersSeeder.php
<?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('123456'), ], [ 'name'=>'User', 'email'=>'user@webmeed.com', 'user_type'=>'User', 'password'=> bcrypt('123456'), ], ]; foreach ($user as $key => $value) { User::create($value); } } }

Now let's run seeder:
Once you have written your seeder, you may need to regenerate Composer's autoloader using the dump-autoloadcommand
Composer dump-autoload
Ok, now we are ready to run.
php artisan db:seed --class=CreateUsersSeeder
Ok, now we are ready to run.
So let's run project using this command:
php artisan serve

Admin User
Email: admin@trickprof.com
Password: 123456

Tags

We are Recommending you:

Leave a comment

Comments