4
votes

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?

3
Do you even tried to make a more authentications? The base for authentication is Auth::attempt method (read more: laravel.com/docs/5.2/authentication#authenticating-users).Grzegorz Gajda
@BasheerAhmed i mean i want to use in laravel 5.2Toàn Tam
That will give you a basic idea of how to start with..Basheer Kharoti
@GrzegorzGajda i am a newbie in laravel ! i just know how to use default user authentication ! if you have done multi authenticate, can you give me some example project ?Toàn Tam

3 Answers

27
votes

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....

6
votes

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());
        } 
    }
}
0
votes

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.