Laravel 8 Multi Auth (Authentication) Example

Hello Dev,

As we speak, i we’ll present you laravel Eight multi auth (authentication) instance. This text will provide you with easy instance of how you can create multi login in laravel 8. you’ll laravel Eight multi authentication instance. On this article, we’ll implement a laravel Eight multi auth (authentication) instance.

So let’s observe few step to create instance of laravel Eight multi auth (authentication) instance.

Preview:-
Laravel 8 Multi Auth (Authentication) Example

Laravel 8 Multi Auth (Authentication) Example

Step 1: Laravel Eight Set up


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

Step 2: Database Configuration

.env


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database identify(weblog)
DB_USERNAME=database username(root)
DB_PASSWORD=database password(root)

Step 3: Migration and Mannequin

database/migrations/000_create_users_table.php


public operate up()
    {
        Schema::create('customers', operate (Blueprint $desk) {
            $table->id();
            $table->string('identify');
            $table->string('e-mail');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

app/Fashions/Consumer.php


<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class Consumer extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes which might be mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'is_admin',
        'password',
    ];

    /**
     * The attributes that must be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that must be solid.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


Now we have to run migration.

so let’s run bellow command:


php artisan migrate

Step 4: Create Auth

Laravel Eight UI Bundle


composer require laravel/ui 

Generate auth


php artisan ui bootstrap --auth 

npm set up

npm run dev

Step 5: Create IsAdmin Middleware

On this step, we have a tendency to want to type admin middleware which will permits solely admin entry customers to it routes. due to this fact let’s produce admin consumer with following steps.


php artisan make:middleware IsAdmin

app/Http/middleware/IsAdmin.php


<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;

class IsAdmin
{
    /**
     * Deal with an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $subsequent
     * @return combined
     */
    public operate deal with($request, Closure $subsequent)
    {
        if(auth()->consumer()->is_admin == 1){
            return $subsequent($request);
        }

        return redirect(‘dwelling’)->with(‘error’,"You do not have admin entry.");
    }
}


app/Http/Kernel.php


protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'is_admin' => AppHttpMiddlewareIsAdmin::class,
    ];

Step 6: Create Route

routes/internet.php


<?php

use IlluminateSupportFacadesRoute;


use AppHttpControllersHomeController;
/*
|--------------------------------------------------------------------------
| Net Routes
|--------------------------------------------------------------------------
|
| Right here is the place you'll be able to register internet routes in your utility. These
| routes are loaded by the RouteServiceProvider inside a bunch which
| comprises the "internet" middleware group. Now create one thing nice!
|
*/

Route::get('/', operate () {
    return view('welcome');
});

Auth::routes();

 Route::get('/dwelling', [AppHttpControllersHomeController::class, 'index'])->identify('dwelling');

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


Step 7: Add Technique on HomeController

app/Http/Controllers/HomeController.php


<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class HomeController extends Controller
{
    /**
     * Create a brand new controller occasion.
     *
     * @return void
     */
    public operate __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Present the appliance dashboard.
     *
     * @return IlluminateContractsSupportRenderable
     */
    public operate index()
    {
        return view('dwelling');
    }

    public operate adminHome()
    {
        return view('adminHome');
    }
}


Step 8: Create Blade file

assets/views/dwelling.blade.php


@extends('layouts.app')

@part('content material')
<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('standing'))
                        <div class="alert alert-success" function="alert">
                            {{ session('standing') }}
                        </div>
                    @endif
                    You might be regular consumer.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection


assets/views/adminHome.blade.php


@extends('layouts.app')

@part('content material')
<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('standing'))
                        <div class="alert alert-success" function="alert">
                            {{ session('standing') }}
                        </div>
                    @endif
                    You might be Admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection


Step 9: Replace on LoginController

app/Http/Controllers/Auth/LoginController.php


<?php



namespace AppHttpControllersAuth;

use AppHttpControllersController;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateHttpRequest;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating customers for the appliance and
    | redirecting them to your property display screen. The controller makes use of a trait
    | to conveniently present its performance to your purposes.
    |
    */

    use AuthenticatesUsers;

    /**
     * The place to redirect customers after login.
     *
     * @var string
     */
    protected $redirectTo = '/dwelling';

    /**
     * Create a brand new controller occasion.
     *
     * @return void
     */
    public operate __construct()
    {
        $this->middleware('visitor')->besides('logout');
    }

    public operate login(Request $request)
    {
        $enter = $request->all();

        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if(auth()->try(array('e-mail' => $enter['email'], 'password' => $enter['password'])))
        {
            if (auth()->consumer()->is_admin == 1) {
                return redirect()->route('admin.dwelling');
            }else{
                return redirect()->route('dwelling');
            }
        }else{
            return redirect()->route('login')
                ->with('error','E-mail-Handle And Password Are Flawed.');
        }

    }
}


Step 10: Create Seeder


php artisan make:seeder CreateUsersSeeder

database/seeds/CreateUsersSeeder.php


<?php
  
use IlluminateDatabaseSeeder;
use AppModelsUser;
   
class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public operate run()
    {
        $consumer = [
            [
               'name'=>'Admin',
               'email'=>'admin@codeplaners.com',
                'is_admin'=>'1',
               'password'=> bcrypt('12345678'),
            ],
            [
               'name'=>'User',
               'email'=>'user@codeplaners.com',
                'is_admin'=>'0',
               'password'=> bcrypt('12345678'),
            ],
        ];
  
        foreach ($consumer as $key => $worth) {
            Consumer::create($worth);
        }
    }
}

Now let’s run seeder:


php artisan db:seed --class=CreateUsersSeeder

Okay, now we’re able to run.


php artisan serve

I hope it’s going to help you…

Komentar

Postingan populer dari blog ini

PHP 8 Multiple Select Dropdown Example

Laravel 8 Get HTTP Hostname

JQuery Drag And Drop Menu Example