Laravel 5 Separate Authentication for Admin and Users

Written by Jigesh Raval on June 8, 2017

LaravelLogo

Welcome to my tutorial about Laravel authentication for Users (Front end) & Admin (Backend).

Laravel is specifically built for web applications and one can expect that any application would need administration section and, of course, front end.

Undoubtedly, Laravel is wonderful application to learn and have as your code base & written with so much of care.

Laravel doesn’t have default arrangements to have two separate authentications for Users & Admin. In this tutorial we’re going to look forward about the authentication logic we can deploy to Laravel.

Before i start, I assume you’ve Laravel default installed.

Prerequisite:

  1. Laravel Default Installed
  2. Front end User table : users
  3. Admin User Table: admin_users

Front end Authentication:

This is really easy and nothing to describe more as you might have ready laravel documentation for authentication.

Open your Terminal or Putty,

Run,

php artisan make:auth

This will install default Laravel front end Authentication including Registration & Login.

Okay so i assume now front end authentication part is done and that was not at all problem since it was already given by laravel default.

Let us add Admin side authentication.

Step:1 Open Web.php(V 5.4) or Routes.php(V 5.4 <) And add following lines

Route::group(['prefix' => 'admin'], function () {
   Route::get('login', 'AdminControllers\AuthController@initContent');
});

Step:2 Now create controller file App\Http\Controllers\AdminControllers\AuthController.php  and define initContent() method we called in router (Web.php or Routes.php)
public function initContent()
{
return view('admin/login');
}

Step:3 Now go to resources/views and create folder ‘admin’ and create new file login.blade.php and copy content from resources/views/auth/login.blade.php

This will create the identical login screen for admin and URL would be (admin/login).

But we still need Admin registration screen so that we can insert user into database.

Admin User Registration Screen

Step:4 add route after admin login route.

Route::get(‘register’, ‘AdminControllers\AuthController@initRegister’);

Step:5 Create method initRegister() in AuthController.php (App\Http\Controllers\AdminControllers\AuthController.php)

public function initRegister()
 {
 return view('admin/register');
 }

Step:6 Create registration view file in resources/views/admin/register.blade.php and copy content from resources/views/auth/register.blade.php. This will create registration screen for admin at url (admin/register)

Step: 7 Open register.blade.php and change action url in Form tag to {{ url(‘admin/register’) }}

Insert Admin Users into admin_user table

Before we move further, let me give you some highlights about what are we going to do next ?

  1. Create guard in Config/Auth.php
  2. Create Providers in Config/Auth.php
  3. Create Database table (admin_users)

Now, Authentication screen is there and let’s do the authentication process.

What are we going to do next ?

  1. Create guard in Config/Auth.php
  2. Create Providers in Config/Auth.php
  3. Create Database table (admin_users)

Step: 8 Create new guard ‘admins’ in Config/Auth.php file

Go to Config/Auth.php and create new guard in array of ‘Guards’.

New array of Guards will look like this,

'guards' => [
 'web' => [
 'driver' => 'session',
 'provider' => 'users',
 ],
'api' => [
 'driver' => 'token',
 'provider' => 'users',
 ],
'admins' => [
 'driver' => 'session',
 'providers' => 'admins'
 ]
 ],

Step: 9 Go to array of Providers that is after the ‘Guards’ array in same Config/Auth.php file and create new provider with Model AdminUser

New array of ‘providers’ will look like this

‘providers’ => [
‘users’ => [
‘driver’ => ‘eloquent’,
‘model’ => App\User::class,
],
‘admins’ => [
‘driver’ => ‘eloquent’,
‘model’ => App\AdminUser::class,
],

// ‘users’ => [
// ‘driver’ => ‘database’,
// ‘table’ => ‘users’,
// ],
],

Step: 10 Create model AdminUser in App Folder (App\AdminUser.php)

Step: 11 assign table variable in AdminUser.php file

protected $table = ‘admin_users’;

Now you’ve new guard ready to handle requests via admin_users table.

We still need to go create Middleware that utilize the new guard ‘admins’ and redirect to the ‘Dashboard’ if Admin use is logged in.

Step 12: Go to app\Http\Middleware and create new Middleware File AdminAuthenticate.php

In the file,
return redirect('/authority/login');
}
return $next($request);
}
}

Let me elaborate above code,

It is simple Middleware file which check weather user is logged in ? if yes, than it will redirect user to Dashboard page.

Step 13: Define Routes (Front end / Admin)

Now i would say your back end part is ready, you need to set your routes.

Go to routes/web.php

Front end routes:

Route::get('/login', 'FrontControllers\LoginController@showLoginForm')->name('login');
 Route::post('login', 'FrontControllers\LoginController@login');
 Route::get('logout', 'FrontControllers\LoginController@logout');
// Registration Routes...
 Route::get('/register', 'FrontControllers\RegisterController@showRegistrationForm');
 Route::post('register', 'FrontControllers\RegisterController@register');
Admin Routes:
Route::group(['prefix' => 'authority'], function () {
 Route::group(['middleware' => ['admins']], function () {
 Route::get('dashboard', 'AdminControllers\DashboardController@initContent');
 });
Route::get('login', 'AdminControllers\LoginController@initContent');
 Route::post('login', 'AdminControllers\LoginController@login');
 Route::get('logout', 'AdminControllers\LoginController@logout');
 });

Description of above routes: I’ve separate folders for FrontControllers as well as AdminControllers, so don’t get confuse, if you’ve any question, do ask me in below form.

How we can keep separate laravel controllers for admin and front end will be discussed in my upcoming tutorial. That will also consist of how you can have THEME based laravel structure where you can define your own theme for front end as well as admin.

Step 14: Create Controllers File

I am pasting controller Files here

A) FrontControllers/LoginController.php

<?php
namespace App\Http\Controllers\FrontControllers;
use App\Http\Controllers\FrontController;
 use Illuminate\Foundation\Auth\AuthenticatesUsers;
 use Auth;
 use Illuminate\Http\Request;
class LoginController extends FrontController
 {
 /*
 |--------------------------------------------------------------------------
 | Login Controller
 |--------------------------------------------------------------------------
 |
 | This controller handles authenticating users for the application and
 | redirecting them to your home screen. The controller uses a trait
 | to conveniently provide its functionality to your applications.
 |
 */
use AuthenticatesUsers;
/**
 * Where to redirect users after login.
 *
 * @var string
 */
 protected $redirectTo = '/home';
/**
 * Create a new controller instance.
 *
 * @return void
 */
 public function __construct()
 {
 parent::__construct();
 $this->middleware('guest', ['except' => 'logout']);
 }
public function showLoginForm()
 {
 return $this->view('front.auth.login');
 }
/**
 * Log the user out of the application.
 *
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */
 public function logout(Request $request)
 {
 Auth::guard('web')->logout();
return redirect('login');
 }
 }

B) FrontControllers/RegisterController.php

<?php
namespace App\Http\Controllers\FrontControllers;
use App\Objects\User;
 use App\Http\Controllers\FrontController;
 use Illuminate\Support\Facades\Validator;
 use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends FrontController
 {
 /*
 |--------------------------------------------------------------------------
 | Register Controller
 |--------------------------------------------------------------------------
 |
 | This controller handles the registration of new users as well as their
 | validation and creation. By default this controller uses a trait to
 | provide this functionality without requiring any additional code.
 |
 */
use RegistersUsers;
/**
 * Where to redirect users after registration.
 *
 * @var string
 */
 protected $redirectTo = '/home';
/**
 * Create a new controller instance.
 *
 * @return void
 */
 public function __construct()
 {
 parent::__construct();
 $this->middleware('guest');
 }
/**
 * Get a validator for an incoming registration request.
 *
 * @param array $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
 protected function validator(array $data)
 {
 return Validator::make($data, [
 'name' => 'required|max:255',
 'email' => 'required|email|max:255|unique:users',
 'password' => 'required|min:6|confirmed',
 ]);
 }
/**
 * Create a new user instance after a valid registration.
 *
 * @param array $data
 * @return User
 */
 protected function create(array $data)
 {
 return User::create([
 'name' => $data['name'],
 'email' => $data['email'],
 'password' => bcrypt($data['password']),
 ]);
 }
public function showRegistrationForm()
 {
 return view('front.auth.register');
 }
 }

 

C) AdminControllers/LoginController.php

<?php
namespace App\Http\Controllers\AdminControllers;
use Illuminate\Http\Request;
 use App\Http\Controllers\AdminController;
 use Illuminate\Foundation\Auth\AuthenticatesUsers;
 use Auth;
class LoginController extends AdminController
 {
 /*
 |--------------------------------------------------------------------------
 | Login Controller
 |--------------------------------------------------------------------------
 |
 | This controller handles authenticating users for the application and
 | redirecting them to your home screen. The controller uses a trait
 | to conveniently provide its functionality to your applications.
 |
 */
 use AuthenticatesUsers;
 /**
 * Where to redirect users after login.
 *
 * @var string
 */
 protected $redirectTo = '/admin/dashboard';
protected $logoutRedirectTo = 'admin/login';
protected $guard = 'admins';
public function __construct()
 {
 parent::__construct();
 $this->middleware('adminguest', ['except' => 'logout']);
 }
public function initContent()
 {
 return $this->view('admin.login');
 }
/**
 * Get the guard to be used during authentication.
 *
 * @return \Illuminate\Contracts\Auth\StatefulGuard
 */
 protected function guard()
 {
 return Auth::guard('admins');
 }
/**
 * Log the user out of the application.
 *
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */
 public function logout(Request $request)
 {
 Auth::guard('admins')->logout();
return redirect($this->logoutRedirectTo);
 }
 }

I am not pasting blade file here instead i will publish a GitHub directory which will be ready-to-go directory.

Feel free to ask me any question regarding Laravel authentication and i would be glad to answer those. Thank you for reading through this long tutorial.

I am planning to publish the video for the same so that may interest you.

Keep learning…!

Here is the working GitHub directory: https://github.com/itinnovator/foundation

Leave a Reply

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