Laravel 7/6 Multi Auth (Authentication) Tutorial
In this post we will give you information about Laravel 7/6 Multi Auth (Authentication) Tutorial. Hear we will give you detail about Laravel 7/6 Multi Auth (Authentication) TutorialAnd how to use it also give you demo for it if it is necessary.
In this tutorial, i would like to share with you how to create laravel 7/6 multiple authentication using middleware. we will create multi auth in laravel 7/6 using middleware. i will write step by step tutorial of creating multiple authentication in laravel 7/6.
I written many tutorials about multi authentication in laravel. in this tutorial we will create multi auth very simple way using middleware with single table. if you want to create multiple authentication using guard than you can follow this tutorial: Laravel multi auth example using Auth guard from scratch and if you want to create multiple authentication with laravel using role and middleware than you can follow this tuto: Laravel 5 – Simple user access control using Middleware
However, in this example, we will create very simple way and you can easily use with your laravel 6 application. so let’s follow this step.
Step 1: Install Laravel 7/6
first of all we need to get fresh Laravel 6 version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration
In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 6. So let’s open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Update Migration and Model
In this step, we need to add new row “is_admin” in users table and model. than we need to run migration. so let’s change that on both file.
database/migrations/000_create_users_table.php
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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');
$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');
}
}
app/User.php
<?php
namespace App;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
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',
];
}
Now we need to run migration.
so let’s run bellow command:
php artisan migrate
Step 4: 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 6 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 require to create admin middleware that will allows only admin access users to that routes. so let’s create admin user with following steps.
php artisan make:middleware IsAdmin
app/Http/middleware/IsAdmin.php
<?php
namespace AppHttpMiddleware;
use Closure;
class IsAdmin
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $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' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
'is_admin' => AppHttpMiddlewareIsAdmin::class,
];
....
Step 6: Create Route
Here, we need to add one more route for admin user home page so let’s add that route in web.php file.
routes/web.php
Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');
Step 7: Add Method on Controller
Here, we need add adminHome() method for admin route in HomeController. so let’s add like as bellow:
app/Http/Controllers/HomeController.php
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return IlluminateContractsSupportRenderable
*/
public function index()
{
return view('home');
}
/**
* Show the application dashboard.
*
* @return IlluminateContractsSupportRenderable
*/
public function adminHome()
{
return view('adminHome');
}
}
Step 8: 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.
resources/views/home.blade.php
@extends('layouts.app')
@section('content')
<div >
<div >
<div >
<div >
<div >Dashboard</div>
<div >
You are normal user.
</div>
</div>
</div>
</div>
</div>
@endsection
resources/views/adminHome.blade.php
@extends('layouts.app')
@section('content')
<div >
<div >
<div >
<div >
<div >Dashboard</div>
<div >
You are Admin.
</div>
</div>
</div>
</div>
</div>
@endsection
Step 9: 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.
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 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
We will create seeder for create new admin and normal user. so let’s create seeder using following command:
php artisan make:seeder CreateUsersSeeder
database/seeds/CreateUsersSeeder.php
<?php
use IlluminateDatabaseSeeder;
use AppUser;
class CreateUsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$user = [
[
'name'=>'Admin',
'email'=>'admin@onlinecode',
'is_admin'=>'1',
'password'=> bcrypt('123456'),
],
[
'name'=>'User',
'email'=>'user@onlinecode',
'is_admin'=>'0',
'password'=> bcrypt('123456'),
],
];
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.
So let’s run project using this command:
php artisan serve
Admin User
Email: admin@onlinecode
Password: 123456
Normal User
Email: user@onlinecode
Password: 123456
You can download code from git: Download Code from Github
I hope it can help you…
Hope this code and post will helped you for implement Laravel 7/6 Multi Auth (Authentication) Tutorial. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs