How to implement multi auth in Laravel 5.4 with example

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

  1. <?php
  2. namespace App;
  3. use IlluminateNotificationsNotifiable;
  4. use IlluminateFoundationAuthUser as Authenticatable;
  5. class User extends Authenticatable
  6. {
  7. use Notifiable;
  8. /**
  9. * The attributes that are mass assignable.
  10. *
  11. * @var array
  12. */
  13. protected $fillable=[
  14. 'name','email','password',
  15. ];
  16. /**
  17. * The attributes that should be hidden for arrays.
  18. *
  19. * @var array
  20. */
  21. protected $hidden=[
  22. 'password','remember_token',
  23. ];
  24. }
<?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

  1. <?php
  2. namespace App;
  3. use IlluminateNotificationsNotifiable;
  4. use IlluminateFoundationAuthUser as Authenticatable;
  5. class Admin extends Authenticatable
  6. {
  7. use Notifiable;
  8. /**
  9. * The attributes that are mass assignable.
  10. *
  11. * @var array
  12. */
  13. protected $fillable=[
  14. 'name','email','password',
  15. ];
  16. /**
  17. * The attributes that should be hidden for arrays.
  18. *
  19. * @var array
  20. */
  21. protected $hidden=[
  22. 'password','remember_token',
  23. ];
  24. }
<?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

  1. Route::group(['middleware'=>['web']],function(){
  2. Route::get('login','UserLoginController@getUserLogin');
  3. Route::post('login',['as'=>'user.auth','uses'=>'UserLoginController@userAuth']);
  4. Route::get('admin/login','AdminLoginController@getAdminLogin');
  5. Route::post('admin/login',['as'=>'admin.auth','uses'=>'AdminLoginController@adminAuth']);
  6. Route::group(['middleware'=>['admin']],function(){
  7.     Route::get('admin/dashboard',['as'=>'admin.dashboard','uses'=>'AdminController@dashboard']);
  8. });
  9. });
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.

  1. <?php
  2. namespace AppHttpMiddleware;
  3. use Closure;
  4. use IlluminateSupportFacadesAuth;
  5. class RedirectIfNotAdmin
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param IlluminateHttpRequest $request
  11. * @param Closure $next
  12. * @param string|null $guard
  13. * @return mixed
  14. */
  15. public functionhandle($request, Closure $next,$guard='admin')
  16. {
  17. if(!Auth::guard($guard)->check()){
  18. returnredirect('admin/login');
  19. }
  20. return$next($request);
  21. }
  22. }
<?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

  1. <?php
  2. namespace AppHttpControllers;
  3. use AppUser;
  4. use AppHttpControllersController;
  5. use IlluminateFoundationAuthAuthenticatesUsers;
  6. use IlluminateHttpRequest;
  7. class UserLoginController extends Controller
  8. {
  9. use AuthenticatesUsers;
  10. protected $redirectTo='/';
  11. /**
  12. * Create a new authentication controller instance.
  13. *
  14. * @return void
  15. */
  16. public function__construct()
  17. {
  18. $this->middleware('guest',['except'=>'logout']);
  19. }
  20. public functiongetUserLogin()
  21. {
  22. returnview('userLogin');
  23. }
  24. public functionuserAuth(Request $request)
  25. {
  26. $this->validate($request,[
  27. 'email'=>'required|email',
  28. 'password'=>'required',
  29. ]);
  30. if(auth()->attempt(['email'=>$request->input('email'),'password'=>$request->input('password')]))
  31. {
  32. $user=auth()->user();
  33. dd($user);
  34. }else{
  35. dd('your username and password are wrong.');
  36. }
  37. }
  38. }
<?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

  1. <?php
  2. namespace AppHttpControllers;
  3. use AppAdmin;
  4. use AppHttpControllersController;
  5. use IlluminateFoundationAuthAuthenticatesUsers;
  6. use IlluminateHttpRequest;
  7. class AdminLoginController extends Controller
  8. {
  9. use AuthenticatesUsers;
  10. protected $redirectTo='/';
  11. /**
  12. * Create a new authentication controller instance.
  13. *
  14. * @return void
  15. */
  16. public function__construct()
  17. {
  18. $this->middleware('guest',['except'=>'logout']);
  19. }
  20. public functiongetAdminLogin()
  21. {
  22. if(auth()->guard('admin')->user())returnredirect()->route('admin.dashboard');
  23. returnview('adminLogin');
  24. }
  25. public functionadminAuth(Request $request)
  26. {
  27. $this->validate($request,[
  28. 'email'=>'required|email',
  29. 'password'=>'required',
  30. ]);
  31. if(auth()->guard('admin')->attempt(['email'=>$request->input('email'),'password'=>$request->input('password')]))
  32. {
  33. returnredirect()->route('admin.dashboard');
  34. }else{
  35. dd('your username and password are wrong.');
  36. }
  37. }
  38. }
<?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

  1. <?php
  2. namespace AppHttpControllers;
  3. use IlluminateHttpRequest;
  4. use AppHttpRequests;
  5. use AppHttpControllersController;
  6. class AdminController extends Controller
  7. {
  8.     public functiondashboard(){
  9.         $user=auth()->guard('admin')->user();
  10. dd($user);
  11.     }
  12. }
<?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

  1. <!DOCTYPEhtml>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="utf-8">
  5. <title>Laravel 5.4 - Multi Auth </title>
  6. <linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. @yield('content')
  10. </body>
  11. </html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.4 - Multi Auth </title>
    <link rel="stylesheet" href="#">
  </head>
  <body>
    @yield('content')
  </body>
</html>



resources/views/userLogin.blade.php

  1. @extends('app')
  2. @section('content')
  3. <divclass="container">
  4. <divclass="row">
  5. <divclass="col-md-8 col-md-offset-2">
  6. <divclass="panel panel-default">
  7. <divclass="panel-heading">User Login</div>
  8. <divclass="panel-body">
  9. <formclass="form-horizontal"role="form"method="POST"action="{{ route('user.auth') }}">
  10. {!! csrf_field() !!}
  11. <divclass="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
  12. <labelclass="col-md-3 control-label">E-Mail</label>
  13. <divclass="col-md-6">
  14. <inputtype="email"class="form-control"name="email"value="{{ old('email') }}">
  15. @if ($errors->has('email'))
  16. <spanclass="help-block">
  17. <strong>{{ $errors->first('email') }}</strong>
  18. </span>
  19. @endif
  20. </div>
  21. </div>
  22. <divclass="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
  23. <labelclass="col-md-3 control-label">Password</label>
  24. <divclass="col-md-6">
  25. <inputtype="password"class="form-control"name="password">
  26. @if ($errors->has('password'))
  27. <spanclass="help-block">
  28. <strong>{{ $errors->first('password') }}</strong>
  29. </span>
  30. @endif
  31. </div>
  32. </div>
  33. <divclass="form-group">
  34. <divclass="col-md-6 col-md-offset-3">
  35. <buttontype="submit"class="btn btn-primary">Login</button>
  36. </div>
  37. </div>
  38. </form>
  39. </div>
  40. </div>
  41. </div>
  42. </div>
  43. </div>
  44. @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

  1. @extends('app')
  2. @section('content')
  3. <divclass="container">
  4. <divclass="row">
  5. <divclass="col-md-8 col-md-offset-2">
  6. <divclass="panel panel-default">
  7. <divclass="panel-heading">Admin Login</div>
  8. <divclass="panel-body">
  9. <formclass="form-horizontal"role="form"method="POST"action="{{ route('admin.auth') }}">
  10. {!! csrf_field() !!}
  11. <divclass="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
  12. <labelclass="col-md-3 control-label">E-Mail</label>
  13. <divclass="col-md-6">
  14. <inputtype="email"class="form-control"name="email"value="{{ old('email') }}">
  15. @if ($errors->has('email'))
  16. <spanclass="help-block">
  17. <strong>{{ $errors->first('email') }}</strong>
  18. </span>
  19. @endif
  20. </div>
  21. </div>
  22. <divclass="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
  23. <labelclass="col-md-3 control-label">Password</label>
  24. <divclass="col-md-6">
  25. <inputtype="password"class="form-control"name="password">
  26. @if ($errors->has('password'))
  27. <spanclass="help-block">
  28. <strong>{{ $errors->first('password') }}</strong>
  29. </span>
  30. @endif
  31. </div>
  32. </div>
  33. <divclass="form-group">
  34. <divclass="col-md-6 col-md-offset-3">
  35. <buttontype="submit"class="btn btn-primary">Login</button>
  36. </div>
  37. </div>
  38. </form>
  39. </div>
  40. </div>
  41. </div>
  42. </div>
  43. </div>
  44. @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

For More Info See :: laravel And github

Leave a Comment

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

7  +  3  =  

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