In some cases, you may need to implement multiple authentication systems within a single Laravel application to cater to different user types or roles. This could be useful for scenarios like admin panels, user dashboards, or API authentication.
To multi (auth) authentication in laravel 10; In this tutorial guide, you will learn how to create multi auth system in Laravel 10 based on specific roles like admin, user, etc.
Laravel 10 Multi Auth With Roles and Permissions Tutorial
Steps to create multiple role and permission based authentication in laravel 10 apps:
- Step 1: Setting up a New Laravel Project
- Step 2: Connecting App to the Database
- Step 3: Setting up migration and model
- Step 4: Create Middleware and Setting up
- Step 5: Define Route
- Step 6: Create Methods in Controller
- Step 7: Create Blade View
- Step 8: Start Development Server
Step 1: Setting up a New Laravel Project
First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:
composer create-project --prefer-dist laravel/laravel LaraMulti
Step 2: Connecting App to the Database
Once you have successfully downloaded laravel app in your system. Then you need to visit your project root directory and find .env file. Andset up database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
Step 3: Setting up migration and model
Next, add is_admin column in the users table using mirgration file. So, Open the creates_users_table.php migration file, which is placed on Database/migration and update the following field for admin.
$table->boolean('is_admin')->nullable();
Next open app/User.php and update the below field name is_admin here:
<?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; class User extends Authenticatable { use HasFactory, 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, add is_admin filed after that will use the below command for creating this field into the database.
php artisan migrate
Now, create a build-in authentication system. Use the below command for creating the default auth system in laravel. And change laravel build-in auth system to multi auth system
This command will create routes, controllers and views files for Laravel Login Authentication and registration. It means to provide a basic laravel login authentication and registration Complete system. Let’s open the command prompt and type the below command.
Then install Laravel 10 UI in your project using the below command:
composer require laravel/ui
Now, execute the below command on terminal for creating login, registration, forget password and reset password blade files:
php artisan ui bootstrap --auth
Then execute the following commands:
npm install npm run dev
Step 4: Create Middleware and Setting up
In this laravel multi auth system, create a middleware for checking the users. Who can access the admin area or who can access the normal user area.
php artisan make:middleware IsAdmin
After creating a middleware go-to app/Http/middleware. Implement the logic here for checking a logged in users. Update the code in this handle function.
<?php namespace App\Http\Middleware; use Closure; 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."); } }
Then register this middleware in the app/Http/Kernel.php. So, open kernal.php and add the following $routeMiddleware property in it:
.... 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, '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 5: Define Route
Create routes and add it on web.php file as like below.
Open routes/web.php file
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\HomeController; Route::get('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');
Step 6: Create Methods in Controller
Now open the HomeController.php file, which is placed on app/Http/Controllers/ directory. Then add the following code into it:
<?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 7: Create Blade View
Now, create two blade view files first is display home page and second is display after login.
Open the resources/views/home.blade. file and update the below code.
@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(auth()->user()->is_admin == 1) <a href="{{url('admin/routes')}}">Admin</a> @else <div class=”panel-heading”>Normal User</div> @endif </div> </div> </div> </div> </div> @endsection
Now, I checked the user profile. If it is admin, it will navigate to the admin area. Otherwise, it will redirect to users area.
Create admin.blade.php file inside resources/views/ directory and update the following code:
@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(auth()->user()->is_admin == 1) <a href="{{url('admin/routes')}}">Admin</a> @else <div class=”panel-heading”>Normal User</div> @endif </div> </div> </div> </div> </div> @endsection
Step 8: Run development server
Now, start the development server using the below command and test our Laravel 10 multi auth system:
php artisan serve
After complete all steps, see the last testing steps for laravel multi auth system :
- First, register a user through the Laravel register.
- Second Change the status is_admin = 1 in users table
- Third Login into a laravel application
Perfect!
I have to create an API on a courier app. It has three roles. Admin, Customer, Driver. How do we authenticate it?