
Laravel multi auth
How to add multi-auth in laravel, is one of the popular questions in google i have seen. I have faced lots of problems and I’m sure there are others too like me.
Here I’m today for sharing what I got after lots of research in google. i have got a solution for using multi auth in laravel 5.4. That is a separate login for admin and users.
Laravel comes with default guard users and there is an option to define more, and we are going to use that feature. so let’s begin the task on how to use multi auth in laravel 5.4.
First of all, install a fresh copy of laravel using a composer or you can download it from Github. Here I’m using the composer to create a project.
composer create-project --prefer-dist laravel/laravel newproject
Here a new project is your project name. After the successful installation of laravel. Create a database, set DBNAME, USERNAME And PASSWORD in .env file and config/database.php file. Now please check that your project is working fine. Access your project in the browser
http://localhost/newproject/public/
if it’s working fine. let go to the next step.
Now we have to create a migration for admin. To do that, please got to your project directory using cmd
Go to your project directory press CTRL+SHIFT and right-click and select open cmd here.
Now run the following code in cmd
php artisan make:migration create_admins_table --create=admins
Migration is created. Open the created migration from yourproject/database/migrations/ add the following code.
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->enum('roles',['superadmin','admin','editor']);
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->enum('status',['0','1']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Save it. and run following code in the composer
php artisan migrate
the above command will create tables in your database. with the above mentions column names, you can change the column as you want. follow laravel official documentation. >Now its time to create a model for Admin
php artisan make:model Model/Admin/Admin
The above command will create a folder inside App folder, Model/Admin, there you can see the newly created Admin.php model. open it and replace with the following code.
namespace AppModelAdmin;
use IlluminateSupportFacadesAuth;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admins';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','roles','status',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function hasAnyRole($roles)
{
if(is_array($roles)) {
foreach ($roles as $role) {
if($this->hasRole($role)){
return true;
}
}
} else {
if($this->hasRole($roles)) {
return true;
}
}
return false;
}
public static function isEditor()
{
if($this->hasRole('editor')) {
return true;
}
return false;
}
public static function isAdmin()
{
if($this->hasRole('admin')) {
return true;
}
return false;
}
public function isSuperAdmin()
{
if($this->hasRole('superadmin')) {
return true;
}
return false;
}
public function hasRole($role)
{
$currentUser = Auth::user()->id;
if($this->where(['id'=>$currentUser,'roles'=> $role])->first()) {
return true;
}
return false;
}
}
Now, go to App/Exceptions/Handler.php and copy following code and paste
namespace AppExceptions;
use Exception;
use IlluminateAuthAuthenticationException;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
IlluminateAuthAuthenticationException::class,
IlluminateAuthAccessAuthorizationException::class,
SymfonyComponentHttpKernelExceptionHttpException::class,
IlluminateDatabaseEloquentModelNotFoundException::class,
IlluminateSessionTokenMismatchException::class,
IlluminateValidationValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @param Exception $exception
* @return IlluminateHttpResponse
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param IlluminateHttpRequest $request
* @param IlluminateAuthAuthenticationException $exception
* @return IlluminateHttpResponse
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'admin':
$login = 'admin.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
}
Next, go to app/Http/Middleware/RedirectIfAuthenticated.php and paste code
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
break;
}
return $next($request);
}
}
Next, Create Admin Controller inside, App/Http/Controllers/Admin/, but action can be performed in two ways, you can create a controller manually or with artisan command, I’m using artisan for this action, for artisan PHP use this code
php artisan make:controller Admin/AdminController
This will create a controller AdminController.php, now open it and add following code
namespace AppHttpControllersAdmin;
use AppModelAdminAdmin;
use IlluminateHttpRequest;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
protected $admin;
public function __construct()
{
$this->admin = new Admin;
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* @return IlluminateHttpResponse
*/
public function index()
{
return view('admin.home');
}
}
Next, create AdminLoginController inside app/Http/Controllers/Admin/Auth/AdminLoginController.php, and add following code
namespace AppHttpControllersAdminAuth;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;
use AppHttpControllersAdminController;
class AdminLoginController extends Controller
{
protected $redirectTo = '/admin';
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
protected function guard()
{
return Auth::guard('admin');
}
public function showLoginForm()
{
return view('admin.auth.admin-login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if ($this->guard()->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
}
Now, go to config/auth.php and paste
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => AppModelAdmin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 15,
],
],
];
Now, Create a route in yourproject/routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::prefix('admin')->group(function() {
Route::get('/', 'AdminAdminController@index')->name('admin.dashboard');
Route::get('/login', 'AdminAuthAdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'AdminAuthAdminLoginController@login')->name('admin.login.submit');
});
Now, its time to create Views, Create an Admin folder inside view directory. Copy all files from View Directory and Paste inside Admin directory including auth directory. if there is not an auth directory inside view, run this command
php artisan make:auth
This will create user authentication files and view files. After copying all files, open them and change
@extends('layouts.app') to @extends('Admin.layouts.app')
in all files inside the Admin folder. Now, open login form, and update Form action to
{{ route('admin.login.submit') }},
Here I’ve renamed default Login.blade to admin-login.blade. It’s done.
You have just created multi-AUTH in Laravel .! Enjoy.

Leave a Reply