Laravel 7 Multiple Authentication Example Tutorial – onlinecode

Laravel 7 Multiple Authentication Example Tutorial – onlinecode

In this post we will give you information about Laravel 7 Multiple Authentication Example Tutorial – onlinecode. Hear we will give you detail about Laravel 7 Multiple Authentication Example Tutorial – onlinecodeAnd how to use it also give you demo for it if it is necessary.

Today, we are going to how to create multiple authentications using the laravel 7 (like front-end login and register and back-end login and register).

Overview

Step 1: Install Laravel

Step 2: Setting Database Configuration

Step 3: Create Table using migration

Step 4: Install the Laravel/UI package

Step 5: Install the Laravel Auth command

Step 6: Create IsAdmin Middleware

Step 7: Modify the Controllers and Model

Step 8: Define The Route

Step 9: Create Blade Files

Step 10: Run Our Laravel Application

Step 1: Install Laravel

We are going to install laravel 7, so first open the command prompt or terminal and go to go to xampp htdocs folder directory using the command prompt. after then run the below command.

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

Step 2: Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel7_multiple_authentication)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Create Table using migration

Now, We need to update the user’s migration tables. so we will update the user’s migration table, see below file in update the code for users table.

<?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->id();
            $table->string('name');
            $table->string('email')->unique();
            $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');
    }
}
?>

Run the below command. after the changes above file.

php artisan migrate

Step 4: Install the Laravel/UI package

We need to laravel UI package so we will install the package using the below command.

composer require laravel/ui

when completed successfully installation of laravel UI package then we will see look like as below type of output.

Using version ^2.0 for laravel/ui
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing laravel/ui (v2.0.1): Downloading (100%)
Writing lock file
Generating optimized autoload files
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.

Step 5: Install the Laravel Auth command

Now, we will install the laravel authentication using the below command.

php artisan ui bootstrap --auth

here, Laravel extracted into a scaffolding separate laravel UI packages.

Bootstrap scaffolding installed successfully.
Please run "npm install && npm run dev" to compile your fresh scaffolding.
Authentication scaffolding generated successfully.

Step 6: Create Middleware

Now, we will create IsAdmin Middleware using the below command and we need some changes in handle method. so you can see the below code.

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.");
    }
}
?>

After complete changes. we need to assign route on routeMiddleware array in app/Http/Kernel.php file. so you can see the below code.

app/Http/Kernel.php

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::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 7: Modify the controller and model

Now here, we need to add the adminHome() method in the HomeController.php file.

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 for admin.
     *
     * @return IlluminateContractsSupportRenderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
}
?>

And second, we need to update the LoginController.php file. so you can follow the below code.

app/Http/Controllers/Auth/LoginController.php

<?php

namespace AppHttpControllersAuth;

use AppHttpControllersController;
use AppProvidersRouteServiceProvider;
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 = 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()->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.');
        }
          
    }
}
?>

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',
    ];
}
?>

Step 8: Define The Route

We will open the web.php in the routes directory and paste below following code.

<?php

/*
|--------------------------------------------------------------------------
| 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', 'HomeController@index')->name('home');
Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');
?>

Step 9: Create Blade Files

here in this step, we need to create a new adminHome.blade.php file or you can copy file of home.blade.php and change the file name to the adminHome.blade.php.

adminHome.blade.php

@extends('layouts.app')
@section('content')
<div >
    <div >
        <div >
            <div >
                <div >Dashboard</div>

                <div >
                    @if (session('status'))
                        <div  role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    You are logged in admin dashboard!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 10: Run Our Laravel ApplicationWe can start the server and run this example using the below command.

php artisan serve

Now we will run our example using the below Url in the browser.

http://127.0.0.1:8000/

Download

Read AlsoLaravel 7 CRUD Operation With Ajax Example

Laravel 7 Pagination Example Tutorial

Please follow and like us:

Hope this code and post will helped you for implement Laravel 7 Multiple Authentication Example Tutorial – onlinecode. 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

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

8  +    =  15

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US