How to implement multi auth in Laravel 5.4 with example

How to implement multi auth in Laravel 5.4 with example

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' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::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 Illuminate\Notifications\Notifiable;
  4. use Illuminate\Foundation\Auth\User 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. }
app/Admin.php
  1. <?php
  2. namespace App;
  3. use Illuminate\Notifications\Notifiable;
  4. use Illuminate\Foundation\Auth\User 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. }
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. });
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 App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\Auth;
  5. class RedirectIfNotAdmin
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @param \Closure $next
  12. * @param string|null $guard
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next, $guard = 'admin')
  16. {
  17. if (!Auth::guard($guard)->check()) {
  18. return redirect('admin/login');
  19. }
  20. return $next($request);
  21. }
  22. }
Step 5: Register middleware

In this step, I will register middleware in kernel.php.

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\RedirectIfNotAdmin::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 App\Http\Controllers;
  3. use App\User;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  6. use Illuminate\Http\Request;
  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 function getUserLogin()
  21. {
  22. return view('userLogin');
  23. }
  24. public function userAuth(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. }
app/Http/Controllers/AdminLoginController.php
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Admin;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  6. use Illuminate\Http\Request;
  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 function getAdminLogin()
  21. {
  22. if (auth()->guard('admin')->user()) return redirect()->route('admin.dashboard');
  23. return view('adminLogin');
  24. }
  25. public function adminAuth(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. return redirect()->route('admin.dashboard');
  34. }else{
  35. dd('your username and password are wrong.');
  36. }
  37. }
  38. }
app/Http/Controllers/AdminController.php
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Http\Requests;
  5. use App\Http\Controllers\Controller;
  6. class AdminController extends Controller
  7. {
  8.     public function dashboard(){
  9.         $user = auth()->guard('admin')->user();
  10. dd($user);
  11.     }
  12. }
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. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Laravel 5.4 - Multi Auth </title>
  6. <link rel="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>
resources/views/userLogin.blade.php
  1. @extends('app')
  2. @section('content')
  3. <div class="container">
  4. <div class="row">
  5. <div class="col-md-8 col-md-offset-2">
  6. <div class="panel panel-default">
  7. <div class="panel-heading">User Login</div>
  8. <div class="panel-body">
  9. <form class="form-horizontal" role="form" method="POST" action="{{ route('user.auth') }}">
  10. {!! csrf_field() !!}
  11. <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
  12. <label class="col-md-3 control-label">E-Mail</label>
  13. <div class="col-md-6">
  14. <input type="email" class="form-control" name="email" value="{{ old('email') }}">
  15. @if ($errors->has('email'))
  16. <span class="help-block">
  17. <strong>{{ $errors->first('email') }}</strong>
  18. </span>
  19. @endif
  20. </div>
  21. </div>
  22. <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
  23. <label class="col-md-3 control-label">Password</label>
  24. <div class="col-md-6">
  25. <input type="password" class="form-control" name="password">
  26. @if ($errors->has('password'))
  27. <span class="help-block">
  28. <strong>{{ $errors->first('password') }}</strong>
  29. </span>
  30. @endif
  31. </div>
  32. </div>
  33. <div class="form-group">
  34. <div class="col-md-6 col-md-offset-3">
  35. <button type="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
resources/views/adminLogin.blade.php
  1. @extends('app')
  2. @section('content')
  3. <div class="container">
  4. <div class="row">
  5. <div class="col-md-8 col-md-offset-2">
  6. <div class="panel panel-default">
  7. <div class="panel-heading">Admin Login</div>
  8. <div class="panel-body">
  9. <form class="form-horizontal" role="form" method="POST" action="{{ route('admin.auth') }}">
  10. {!! csrf_field() !!}
  11. <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
  12. <label class="col-md-3 control-label">E-Mail</label>
  13. <div class="col-md-6">
  14. <input type="email" class="form-control" name="email" value="{{ old('email') }}">
  15. @if ($errors->has('email'))
  16. <span class="help-block">
  17. <strong>{{ $errors->first('email') }}</strong>
  18. </span>
  19. @endif
  20. </div>
  21. </div>
  22. <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
  23. <label class="col-md-3 control-label">Password</label>
  24. <div class="col-md-6">
  25. <input type="password" class="form-control" name="password">
  26. @if ($errors->has('password'))
  27. <span class="help-block">
  28. <strong>{{ $errors->first('password') }}</strong>
  29. </span>
  30. @endif
  31. </div>
  32. </div>
  33. <div class="form-group">
  34. <div class="col-md-6 col-md-offset-3">
  35. <button type="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

Phone: (+91) 8800417876
Noida, 201301
okey metin2 pvp serverler metin2 pvp
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort tuzla escort pendik escort ümraniye escort kartal escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort
hatay escort nevsehir escort nigde escort kirikkale escort batman escort osmaniye escort kirklareli escort tokat escort rize escort adiyaman escort gumushane escort batman escort
cialis satış cialis fiyat cialis 20 mg cialis 100 mg cialis 5 mg fiyat

viagra fiyatı

viagra 100 mg fiyat

viagra sipariş

orjinal viagra

viagra satın al

izmir escort
ataşehir escort
kocaeli escort izmit escort bayan gebze escort izmit sınırsız escort escort bursa tuzla escort aydınlı escort orhanlı escort bursa escort escort bayan istanbul escort istanbul sınırsız escort istanbul bayan escort izmit escort izmit escort kocaeli escort sisli escort mecidiyekoy escort bursa escort bayan bursa görükle escort maltepe escort goztepe escort yakacik-yeni-escort bursa sınırsız escort sisli escort bayan taksim escort bursa escort porno izle sikiş izle atasehir escort antalya escort
ankara escort marmaris escort bursa escort mersin escort antalya escort izmir escort samsun escort bodrum escort çeşme escort kuşadası escort adana escort eskişehir escort gaziantep escort esenyurt escort pendik escort tuzla escort fatih escort ümraniye escort mecidiyeköy escort kartal escort bahçelievler escort bahçeşehir escort ataşehir escort bakırköy escort nişantaşı escort avcılar escort büyükçekmece escort kurtkoy escort konya escort beşiktaş escort taksim escort beylikdüzü escort malatya escort sakarya escort şişli escort maltepe escort kadıköy escort ataköy escort bostancı escort şirinevler escort bağcılar escort üsküdar escort etiler escort başaksehir escort ortaköy escort kağıthane escort sultangazi escort halkalı escort çekmeköy escort şaşkınbakkal escort mamak escort sincan escort keçiören escort çankaya escort beypazarı escort akyurt escort pursaklar escort kahramankazan escort göztepe escort alsancak escort bornova escort buca escort karabaglar escort karşıyaka escort konak escort narlıdere escort izmit escort başiskele escort kandira escort körfez escort karamürsel escort dilovası escort gölcük escort gebze escort kocaeli escort kayseri escort elazığ escort denizli escort diyarbakir escort adana escort ankara escort izmir escort antalya escort gaziantep escort kayseri escort konya escort mersin escort denizli escort kocaeli escort diyarbakır escort
bedava bahis