Multi Auth with single user table in laravel 5.2 - php

I want to Multi Auth with single table in laravel 5.2.
I tried this way. But frontend login working.
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
return [
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'database',
'table' => 'user',
'model' => App\User::class,
],
'admin' => [
'driver' => 'database',
'table' => 'user',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
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('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}

In your AdminAuth/AuthController.php.
public function guard()
{
return auth()->guard('admin');
}
and instead of give table name inside providers put protected $table = 'users' in your Admin model.
You can see this for further more details: https://scotch.io/#sukelali/how-to-create-multi-table-authentication-in-laravel

You don't need to use a guard here, Instead; you can use middleware here. Add a user type column here in user table and then create middleware for that.

Related

Laravel Authentication for multiple users

I have 4 types of users in my application and details are stored in 4 different tables, so how can I implement Laravel's Authentication?
Route::post('/adlogin', 'mainController#adminlogin');
Route::get('/sellerlogin', function () {
return view('seller.pages.login');
});
Route::post('/sellerlog_in', 'mainController#sellerlogin');
Use this as your controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//Use Dependencies
use Auth;
class AdminLoginController extends Controller
{
Middleware used here is admin which you have to create in config/auth.php
public function __construct()
{
$this->middleware('guest:admin', ['except'=>'logout']);
}
Create a view for your admin Login
public function showLoginForm()
{
return view('auth.admin_login');
}
public function login(Request $request)
{
//Validate the Form Data
$this->validate($request, [
'email'=>'required|email',
'password'=>'required|min:5'
]);
//Attempt to log the Admin In
$email= $request->email;
$password= $request->password;
$remember= $request->remember;
After Successfully login where you want to redirect like here I am redirecting
toadmin.dashboard
//If Successful redirect to intended location
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password], $remember)) {
return redirect()->intended(route('admin.dashboard'));
}
//If Unsuccessful redirect back to login form with form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
/**
* Log the Admin out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard('admin')->logout();
return redirect()->route('admin.login');
}
}
After logout redirect back to login page
Make sure you are using right guard for right User. Create same functionality for more user types as you want create guards for them.
In config/app.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
As admin and admin-api created here create for your user types
Add providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
At last for resetting passwords use this.
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 10,
],
],
In http/middleware/redirectIfAuthenticated.php add this to your handle function
//Check for admin login guard
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
break;
}
You can add more cases for your user types.
This is all you want to create multi auth. As you created different table for different roles you have to follow this process.
Create LoginController for all user types or use your logic to log them in.
Add your guards for every user type in auth.php
Add your cases to RedirectIfAuthenticated
You can use the laravel-permission package.This package allows you to manage user permissions and roles in a database.

Custom Authentication in laravel 5.5 Not logging in?

I am learning laravel and i decided to make a custom authentication in laravel . I could register my users but when i try to login i get this error ?
Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given,
These are my resources
My AdminUser Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class AdminUser extends Eloquent implements AuthenticatableContract,AuthorizableContract
{
public $table = "admin_users";
use Notifiable;
use AuthenticableTrait;
use Authorizable;
protected $fillable = [
'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AdminUserController
<?php
namespace App\Http\Controllers;
use App\AdminUser;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use Auth;
use Response;
class AdminUserController extends Controller {
use AuthenticatesUsers;
/**
* the model instance
* #var AdminUser
*/
protected $user;
/**
* The Guard implementation.
*
* #var Authenticator
*/
protected $admin;
/**
* Create a new authentication controller instance.
*
* #param Authenticator $admin
* #return void
*/
public function __construct(Guard $admin, AdminUser $user)
{
$user = AdminUser::first();
Auth::login($user);
$this->middleware('admin', ['except' => ['getLogout']]);
}
/**
* Show the application registration form.
*
* #return Response
*/
public function getRegister()
{
return view('admin/admin_users/register');
}
/**
* Handle a registration request for the application.
*
* #param RegisterRequest $request
* #return Response
*/
public function postRegister(RegisterRequest $request)
{
AdminUser::create([
'email' => $request->email,
'password' => bcrypt($request->password),
]);
return redirect('backend-admin/dashboard');
}
/**
* Show the application login form.
*
* #return Response
*/
public function getLogin()
{
return view('admin/admin_users/login');
}
/**
* Handle a login request to the application.
*
* #param LoginRequest $request
* #return Response
*/
public function postLogin(LoginRequest $request)
{
if (Auth::guard('admin')->attempt($request->only('email', 'password')))
{
return redirect()->intended('/backend-admin/dashboard');
}
return redirect('/backend-admin')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
/**
* Log the user out of the application.
*
* #return Response
*/
public function getLogout()
{
Auth::guard('admin')->logout();
return redirect('/backend-admin');
}
protected function guard()
{
return Auth::guard();
}
}
My VerifyAdmin Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
class VerifyAdmin
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $admin;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
// dd($auth);
$this->admin = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->admin->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('backend-admin');
}
}
return $next($request);
}
}
I also defined guards in auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Also defined middleware in kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\VerifyAdmin::class,
Feel free to correct me if i am wrong anywhere or if i have missed anything .
I found what was bugging my program , i did defined guard function in my controller but forget to add the guard in function , i fixed it by defining guard.
I think the problem are those 2 lines:
$user = AdminUser::first();
Auth::login($user);
What's the point of running it? First of all, I see you have here login action and it seems you automatically login admin when on login page - it doesn't make much sense.
Also those 2 lines won't do anything that should be done I think - because when admin logs in, well you log him in so there's no point to login him in each request assuming you are using sessions.
You need to change the admin provider name from admin to admins.
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [ // ***this is the change that should be made***
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];

I am trying to implement laravel 5.2 multiple authentication for user and admin . But authentication user provider[] is not defined error is given

I have followed this questions asnwer
Can anyone explain Laravel 5.2 Multi Auth with example
to implement multiple table authentication using admin and user table . I have done all steps stated above such as added admin as provider , guard in config/auth.php, created auth controller for admin , created a middleware for admin . But after i run my project it say authentication user provider[] is not defined . But i defined provider for admin and user in config/auth.php .I have used different login and registration form, controller for user and admin.When the user or admin logged in then i want to show user or admin name in nav bar. To do this I used auth guard as stated in laravel docs(the code in attachment of master file html) . I have stucked with this error for 6 days . I need your help eagerly . Here is my attaches
config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
routes.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
app/Http/Controllers/AdminAuth/AuthController.php
namespace App\Http\Controllers\AdminAuth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
//protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
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',
]);
}
protected function create(array $data)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
}
Admin.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Contracts\View\View;
class AdminController extends Controller
{
protected $guard = 'admin';
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
Admin middleware
<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfNotAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
Master layout for showing admin
<!-- Authentication Links -->
#if (Auth::guard('admin')->guest())
<li>Login</li>
<li>Register</li>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::guard('admin')->user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li><i class="fa fa-btn fa-sign-out"></i>Logout</li>
</ul>
</li>
#endif
I Think this will be helpful.
http://blog.sarav.co/multiple-authentication-in-laravel/
Why don't you give it a try using the built in user model and extending admin with it.

Redirect loop when using multiple auth guards in Laravel 5

I'm trying to set up two authentication guards: internal (for normal browser requests) and api for AJAX requests. api is the default guard, but I'm focusing on getting the internal-guard to work, for now.
This is my config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'clients',
],
'guards' => [
'internal' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
This is my routes.php:
<?php
Route::group([
'domain' => 'internal.example.com',
'middleware' => ['web', 'auth:internal']
], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
});
Route::group([
'domain' => 'internal.example.com',
'middleware' => [ 'web']
], function () {
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
Route::get('/logout', 'InternalAuth\InternalAuthController#logout');
});
This is InternalAuthController:
<?php
namespace App\Http\Controllers\InternalAuth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class InternalAuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $guard = 'internal';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* 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|confirmed|min:6',
]);
}
/**
* 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']),
]);
}
}
Seems fine to me. But when I go to /, /home or /login in my browser, I end up in a redirect loop.
I'm missing something... Any ideas?
/login points to InternalAuth\InternalAuthController#login. login() is a method of Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers (used by InternalAuth), but it is not responsible for returning the view or responding to post requests. This is a job for getLogin and postLogin.
So, I needed to change this in the routes.php:
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
To this:
Route::get('/login', 'InternalAuth\InternalAuthController#getLogin');
Route::post('/login', 'InternalAuth\InternalAuthController#postLogin');

How to use multi Auth in laravel 5.2 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know how to use multi authenticate in laravel 5.2 ! I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?
You need two tables users and admins
Run command following command to create built in auth
php artisan make:auth
Two models Users(Already exist) and Admin
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
Now open config/auth.php and make the following changes
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
Create a new Middleware RedirectIfNotAdmin
<?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);
}
}
Changes in Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder
Open the file Http/Controller/Adminauth/AuthController.php and make the following changes
<?php
namespace App\Http\Controllers\Adminauth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (Auth::guard('admin')->check())
{
return redirect('/admin');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
public function resetPassword()
{
return view('admin.auth.passwords.email');
}
public function logout(){
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/
create new file Http/Controller/admin/employee.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use App\Admin;
class Employee extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
move to resources/views create new folder resources/views/admin
copy
resources/views/auth, resources/views/layouts & resources/views/home.blade.php
and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like
#extends('admin.layouts.app')
and your Http/routes.php look like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/login','Adminauth\AuthController#showLoginForm');
Route::post('/admin/login','Adminauth\AuthController#login');
Route::get('/admin/password/reset','Adminauth\PasswordController#resetPassword');
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::get('/admin/logout','Adminauth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'Adminauth\AuthController#showRegistrationForm');
Route::post('admin/register', 'Adminauth\AuthController#register');
Route::get('/admin', 'Admin\Employee#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Thats it open your site in browser and check
and for admin yoursiteurl/admin
Enjoy....
First, we create two models: user and admin
Then, we update the config/auth.php file:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
Now, modify the app/Http/kernel.php file:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],
'api' => [
'throttle:60,1',
],
];
Create LoginController and set the following code in it.
Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().
namespace App\Http\Controllers;
use Auth, Input;
use App\User;
use App\Admin;
class LoginController extends Controller
{
public function userLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('user');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('user.login');
}
}
public function adminLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('admin');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('admin.login');
}
}
public function profile(){
if(auth()->guard('admin')->check()){
pr(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
pr(auth()->guard('user')->user()->toArray());
}
}
}
In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.
This approach helps in avoiding the unnecessary headache of creating different user roles or types.
Though this may not sound ideal, but helps in saving lots of time.

Categories