Hi Dev,
Today, i we will show you laravel 8 multi auth (authentication) example. This article will give you simple example of how to create multi login in laravel 8. you will laravel 8 multi authentication example. In this article, we will implement a laravel 8 multi auth (authentication) example.
So let’s follow few step to create example of laravel 8 multi auth (authentication) example.
Preview:-
Step 1: Laravel 8 Install
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration
.env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database name(blog) DB_USERNAME=database username(root) DB_PASSWORD=database password(root)
Step 3: Migration and Model
database/migrations/000_create_users_table.php
public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->timestamp('email_verified_at')->nullable(); $table->boolean('is_admin')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }
app/Models/User.php
<?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; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var string[] */ protected $fillable = [ 'name', 'email', 'is_admin', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }
Now we need to run migration.
so let’s run bellow command:
php artisan migrate
Step 4: Create Auth
Laravel 8 UI Package
composer require laravel/ui
Generate auth
php artisan ui bootstrap --auth
npm install
npm run dev
Step 5: Create IsAdmin Middleware
In this step, we tend to need to form admin middleware that may permits solely admin access users to it routes. therefore let’s produce admin user with following steps.
php artisan make:middleware IsAdmin
app/Http/middleware/IsAdmin.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; 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."); } }
app/Http/Kernel.php
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, 'is_admin' => \App\Http\Middleware\IsAdmin::class, ];
Step 6: Create Route
routes/web.php
<?php use Illuminate\Support\Facades\Route; 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', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::get('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');
Step 7: Add Method on HomeController
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'); } public function adminHome() { return view('adminHome'); } }
Step 8: Create Blade file
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"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif You are normal user. </div> </div> </div> </div> </div> @endsection
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"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif You are Admin. </div> </div> </div> </div> </div> @endsection
Step 9: Update on LoginController
app/Http/Controllers/Auth/LoginController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; 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 = '/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.'); } } }
Step 10: Create Seeder
php artisan make:seeder CreateUsersSeeder
database/seeds/CreateUsersSeeder.php
<?php use Illuminate\Database\Seeder; use App\Models\User; class CreateUsersSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $user = [ [ '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 ($user as $key => $value) { User::create($value); } } }
Now let’s run seeder:
php artisan db:seed --class=CreateUsersSeeder
Ok, now we are ready to run.
php artisan serve
I hope it will assist you…