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 SettingIn 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
- <?php
- namespace App;
- use Illuminate\Notifications\Notifiable;
- use Illuminate\Foundation\Auth\User 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 Illuminate\Notifications\Notifiable;
- use Illuminate\Foundation\Auth\User 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',
- ];
- }
- 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']);
- });
- });
In this step, I will create a new middleware for admin in following path app/Http/Middleware.
- <?php
- namespace App\Http\Middleware;
- use Closure;
- use Illuminate\Support\Facades\Auth;
- class RedirectIfNotAdmin
- {
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $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);
- }
- }
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
- <?php
- namespace App\Http\Controllers;
- use App\User;
- use App\Http\Controllers\Controller;
- use Illuminate\Foundation\Auth\AuthenticatesUsers;
- use Illuminate\Http\Request;
- 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.');
- }
- }
- }
- <?php
- namespace App\Http\Controllers;
- use App\Admin;
- use App\Http\Controllers\Controller;
- use Illuminate\Foundation\Auth\AuthenticatesUsers;
- use Illuminate\Http\Request;
- 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.');
- }
- }
- }
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Http\Requests;
- use App\Http\Controllers\Controller;
- class AdminController extends Controller
- {
- public function dashboard(){
- $user = auth()->guard('admin')->user();
- dd($user);
- }
- }
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
- <!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>
- @extends('app')
- @section('content')
- <div class="container">
- <div class="row">
- <div class="col-md-8 col-md-offset-2">
- <div class="panel panel-default">
- <div class="panel-heading">User Login</div>
- <div class="panel-body">
- <form class="form-horizontal" role="form" method="POST" action="{{ route('user.auth') }}">
- {!! csrf_field() !!}
- <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
- <label class="col-md-3 control-label">E-Mail</label>
- <div class="col-md-6">
- <input type="email" class="form-control" name="email" value="{{ old('email') }}">
- @if ($errors->has('email'))
- <span class="help-block">
- <strong>{{ $errors->first('email') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
- <label class="col-md-3 control-label">Password</label>
- <div class="col-md-6">
- <input type="password" class="form-control" name="password">
- @if ($errors->has('password'))
- <span class="help-block">
- <strong>{{ $errors->first('password') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-6 col-md-offset-3">
- <button type="submit" class="btn btn-primary">Login</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- @endsection
- @extends('app')
- @section('content')
- <div class="container">
- <div class="row">
- <div class="col-md-8 col-md-offset-2">
- <div class="panel panel-default">
- <div class="panel-heading">Admin Login</div>
- <div class="panel-body">
- <form class="form-horizontal" role="form" method="POST" action="{{ route('admin.auth') }}">
- {!! csrf_field() !!}
- <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
- <label class="col-md-3 control-label">E-Mail</label>
- <div class="col-md-6">
- <input type="email" class="form-control" name="email" value="{{ old('email') }}">
- @if ($errors->has('email'))
- <span class="help-block">
- <strong>{{ $errors->first('email') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
- <label class="col-md-3 control-label">Password</label>
- <div class="col-md-6">
- <input type="password" class="form-control" name="password">
- @if ($errors->has('password'))
- <span class="help-block">
- <strong>{{ $errors->first('password') }}</strong>
- </span>
- @endif
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-6 col-md-offset-3">
- <button type="submit" class="btn btn-primary">Login</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- @endsection