How to implement multi auth in Laravel 5.4 with example
In this post we will give you information about How to implement multi auth in Laravel 5.4 with example. Hear we will give you detail about How to implement multi auth in Laravel 5.4 with exampleAnd how to use it also give you demo for it if it is necessary.
Implementing authentication is much easier in Laravel 5.4 and you will get authentication file in following path config/auth.php
.
In Laravel 5.4, web guard is a default authentication guard that is used to authenticate for web based application.
For a big application, it is very necessary to apply authentication for security reason.
In this tutorial, you will know the simple authentication with multiple guards.
Step 1: Configure Auth Setting
In this step, i will edit the config/auth.php
.
// Authenticating guards 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], ], // Providers 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => AppUser::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => AppAdmin::class, ] ],
In above setting, you will see there are three separate guards – web, api and admin, Each have their own provider with different model.
When you use single default authentication system then you get the authenticated user data in following way :
$user = Auth::user(); dd($user);
But when you are working with multiple guards then you must call an additional guard() method to get the authenticated user data:
$user = Auth::guard('admin')->user(); // Or... $user = auth()->guard('admin')->user(); dd($user);
Step 2: User and Admin Models
In this step, i will create two model to authenticate user and admin from different table’s data. By default you will get the user model with laravel fresh installation and you will have to create one admin model.
app/User.php
- <?php
- namespace App;
- use IlluminateNotificationsNotifiable;
- use IlluminateFoundationAuthUser as Authenticatable;
- class User extends Authenticatable
- {
- use Notifiable;
- /**
- * The attributes that are mass assignable.
- *
- * @var array
- */
- protected $fillable=[
- 'name','email','password',
- ];
- /**
- * The attributes that should be hidden for arrays.
- *
- * @var array
- */
- protected $hidden=[
- 'password','remember_token',
- ];
- }
<?php namespace App; use IlluminateNotificationsNotifiable; use IlluminateFoundationAuthUser as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
app/Admin.php
- <?php
- namespace App;
- use IlluminateNotificationsNotifiable;
- use IlluminateFoundationAuthUser as Authenticatable;
- class Admin extends Authenticatable
- {
- use Notifiable;
- /**
- * The attributes that are mass assignable.
- *
- * @var array
- */
- protected $fillable=[
- 'name','email','password',
- ];
- /**
- * The attributes that should be hidden for arrays.
- *
- * @var array
- */
- protected $hidden=[
- 'password','remember_token',
- ];
- }
<?php namespace App; use IlluminateNotificationsNotifiable; use IlluminateFoundationAuthUser as Authenticatable; class Admin extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
Step 3: Add Route
- Route::group(['middleware'=>['web']],function(){
- Route::get('login','UserLoginController@getUserLogin');
- Route::post('login',['as'=>'user.auth','uses'=>'UserLoginController@userAuth']);
- Route::get('admin/login','AdminLoginController@getAdminLogin');
- Route::post('admin/login',['as'=>'admin.auth','uses'=>'AdminLoginController@adminAuth']);
- Route::group(['middleware'=>['admin']],function(){
- Route::get('admin/dashboard',['as'=>'admin.dashboard','uses'=>'AdminController@dashboard']);
- });
- });
Route::group(['middleware' => ['web']], function () { Route::get('login', 'UserLoginController@getUserLogin'); Route::post('login', ['as'=>'user.auth','uses'=>'UserLoginController@userAuth']); Route::get('admin/login', 'AdminLoginController@getAdminLogin'); Route::post('admin/login', ['as'=>'admin.auth','uses'=>'AdminLoginController@adminAuth']); Route::group(['middleware' => ['admin']], function () { Route::get('admin/dashboard', ['as'=>'admin.dashboard','uses'=>'AdminController@dashboard']); }); });
Step 4: Creating a middleware for admin
In this step, I will create a new middleware for admin in following path app/Http/Middleware.
- <?php
- namespace AppHttpMiddleware;
- use Closure;
- use IlluminateSupportFacadesAuth;
- class RedirectIfNotAdmin
- {
- /**
- * Handle an incoming request.
- *
- * @param IlluminateHttpRequest $request
- * @param Closure $next
- * @param string|null $guard
- * @return mixed
- */
- public functionhandle($request, Closure $next,$guard='admin')
- {
- if(!Auth::guard($guard)->check()){
- returnredirect('admin/login');
- }
- return$next($request);
- }
- }
<?php namespace AppHttpMiddleware; use Closure; use IlluminateSupportFacadesAuth; class RedirectIfNotAdmin { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = 'admin') { if (!Auth::guard($guard)->check()) { return redirect('admin/login'); } return $next($request); } }
Step 5: Register middleware
In this step, I will register middleware in kernel.php
.
protected $routeMiddleware = [ 'admin' => AppHttpMiddlewareRedirectIfNotAdmin::class, ];
Step 6: Create Controller
In this step, I will create three controller “AdminLoginController.php”, “UserLoginController.php” and “AdminController.php”.
app/Http/Controllers/UserLoginController.php
- <?php
- namespace AppHttpControllers;
- use AppUser;
- use AppHttpControllersController;
- use IlluminateFoundationAuthAuthenticatesUsers;
- use IlluminateHttpRequest;
- class UserLoginController extends Controller
- {
- use AuthenticatesUsers;
- protected $redirectTo='/';
- /**
- * Create a new authentication controller instance.
- *
- * @return void
- */
- public function__construct()
- {
- $this->middleware('guest',['except'=>'logout']);
- }
- public functiongetUserLogin()
- {
- returnview('userLogin');
- }
- public functionuserAuth(Request $request)
- {
- $this->validate($request,[
- 'email'=>'required|email',
- 'password'=>'required',
- ]);
- if(auth()->attempt(['email'=>$request->input('email'),'password'=>$request->input('password')]))
- {
- $user=auth()->user();
- dd($user);
- }else{
- dd('your username and password are wrong.');
- }
- }
- }
<?php namespace AppHttpControllers; use AppUser; use AppHttpControllersController; use IlluminateFoundationAuthAuthenticatesUsers; use IlluminateHttpRequest; class UserLoginController extends Controller { use AuthenticatesUsers; protected $redirectTo = '/'; /** * Create a new authentication controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'logout']); } public function getUserLogin() { return view('userLogin'); } public function userAuth(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]); if (auth()->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { $user = auth()->user(); dd($user); }else{ dd('your username and password are wrong.'); } } }
app/Http/Controllers/AdminLoginController.php
- <?php
- namespace AppHttpControllers;
- use AppAdmin;
- use AppHttpControllersController;
- use IlluminateFoundationAuthAuthenticatesUsers;
- use IlluminateHttpRequest;
- class AdminLoginController extends Controller
- {
- use AuthenticatesUsers;
- protected $redirectTo='/';
- /**
- * Create a new authentication controller instance.
- *
- * @return void
- */
- public function__construct()
- {
- $this->middleware('guest',['except'=>'logout']);
- }
- public functiongetAdminLogin()
- {
- if(auth()->guard('admin')->user())returnredirect()->route('admin.dashboard');
- returnview('adminLogin');
- }
- public functionadminAuth(Request $request)
- {
- $this->validate($request,[
- 'email'=>'required|email',
- 'password'=>'required',
- ]);
- if(auth()->guard('admin')->attempt(['email'=>$request->input('email'),'password'=>$request->input('password')]))
- {
- returnredirect()->route('admin.dashboard');
- }else{
- dd('your username and password are wrong.');
- }
- }
- }
<?php namespace AppHttpControllers; use AppAdmin; use AppHttpControllersController; use IlluminateFoundationAuthAuthenticatesUsers; use IlluminateHttpRequest; class AdminLoginController extends Controller { use AuthenticatesUsers; protected $redirectTo = '/'; /** * Create a new authentication controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'logout']); } public function getAdminLogin() { if (auth()->guard('admin')->user()) return redirect()->route('admin.dashboard'); return view('adminLogin'); } public function adminAuth(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]); if (auth()->guard('admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { return redirect()->route('admin.dashboard'); }else{ dd('your username and password are wrong.'); } } }
app/Http/Controllers/AdminController.php
- <?php
- namespace AppHttpControllers;
- use IlluminateHttpRequest;
- use AppHttpRequests;
- use AppHttpControllersController;
- class AdminController extends Controller
- {
- public functiondashboard(){
- $user=auth()->guard('admin')->user();
- dd($user);
- }
- }
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class AdminController extends Controller { public function dashboard(){ $user = auth()->guard('admin')->user(); dd($user); } }
Step 7: Create Login View for User and Admin
In this last step, I will create a login template for user and admin. First i will create a master layout for user and admin login view.
resources/views/app.blade.php
- <!DOCTYPEhtml>
- <htmllang="en">
- <head>
- <metacharset="utf-8">
- <title>Laravel 5.4 - Multi Auth </title>
- <linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
- </head>
- <body>
- @yield('content')
- </body>
- </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Laravel 5.4 - Multi Auth </title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body> @yield('content') </body> </html>
resources/views/userLogin.blade.php
- @extends('app')
- @section('content')
- <divclass="container">
- <divclass="row">
- <divclass="col-md-8 col-md-offset-2">
- <divclass="panel panel-default">
- <divclass="panel-heading">User Login</div>
- <divclass="panel-body">
- <formclass="form-horizontal"role="form"method="POST"action="{{ route('user.auth') }}">
- {!! csrf_field() !!}
- <divclass="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
- <labelclass="col-md-3 control-label">E-Mail</label>
- <divclass="col-md-6">
- <inputtype="email"class="form-control"name="email"value="{{ old('email') }}">
- @if ($errors->has('email'))
- <spanclass="help-block">
- <strong>{{ $errors->first('email') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <divclass="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
- <labelclass="col-md-3 control-label">Password</label>
- <divclass="col-md-6">
- <inputtype="password"class="form-control"name="password">
- @if ($errors->has('password'))
- <spanclass="help-block">
- <strong>{{ $errors->first('password') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <divclass="form-group">
- <divclass="col-md-6 col-md-offset-3">
- <buttontype="submit"class="btn btn-primary">Login</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- @endsection
@extends('app') @section('content') <div > <div > <div > <div > <div >User Login</div> <div > <form role="form" method="POST" action="{{ route('user.auth') }}"> {!! csrf_field() !!} <div > <label >E-Mail</label> <div > <input type="email" name="email" value="{{ old('email') }}"> @if ($errors->has('email')) <span > <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> </div> <div > <label >Password</label> <div > <input type="password" name="password"> @if ($errors->has('password')) <span > <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> </div> <div > <div > <button type="submit" >Login</button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
resources/views/adminLogin.blade.php
- @extends('app')
- @section('content')
- <divclass="container">
- <divclass="row">
- <divclass="col-md-8 col-md-offset-2">
- <divclass="panel panel-default">
- <divclass="panel-heading">Admin Login</div>
- <divclass="panel-body">
- <formclass="form-horizontal"role="form"method="POST"action="{{ route('admin.auth') }}">
- {!! csrf_field() !!}
- <divclass="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
- <labelclass="col-md-3 control-label">E-Mail</label>
- <divclass="col-md-6">
- <inputtype="email"class="form-control"name="email"value="{{ old('email') }}">
- @if ($errors->has('email'))
- <spanclass="help-block">
- <strong>{{ $errors->first('email') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <divclass="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
- <labelclass="col-md-3 control-label">Password</label>
- <divclass="col-md-6">
- <inputtype="password"class="form-control"name="password">
- @if ($errors->has('password'))
- <spanclass="help-block">
- <strong>{{ $errors->first('password') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <divclass="form-group">
- <divclass="col-md-6 col-md-offset-3">
- <buttontype="submit"class="btn btn-primary">Login</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- @endsection
@extends('app') @section('content') <div > <div > <div > <div > <div >Admin Login</div> <div > <form role="form" method="POST" action="{{ route('admin.auth') }}"> {!! csrf_field() !!} <div > <label >E-Mail</label> <div > <input type="email" name="email" value="{{ old('email') }}"> @if ($errors->has('email')) <span > <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> </div> <div > <label >Password</label> <div > <input type="password" name="password"> @if ($errors->has('password')) <span > <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> </div> <div > <div > <button type="submit" >Login</button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Now you can try this code into your application when you need to implement multiple authentication in Laravel 5.4.
Hope this code and post will helped you for implement How to implement multi auth in Laravel 5.4 with example. 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