Laravel 5.2 multi auth example using Auth guard from scratch
In this post we will give you information about Laravel 5.2 multi auth example using Auth guard from scratch. Hear we will give you detail about Laravel 5.2 multi auth example using Auth guard from scratchAnd how to use it also give you demo for it if it is necessary.
Multiple authentication is very important in big application of laravel. If you work on large project then you mostly prefer to diferente tables, like you always prefer “users” table for site user registration and “admins” table for admin user that way make strong security. we always use Auth for making user authentication but you have question how to make admins with auth then you can do easily by following step.
Step 1: Auth Config Setting
In this step we will add new admin guard from auth.php file of config directory. so first open auth.php file and add bellow code.
config/auth.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' => AppUser::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => AppAdmin::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,
],
],
];
Step 2: Create Models
In this step we have to create two model for User and Admin. I think we have already User.php model will available but make sure just compare code is the same or not. so fist check bellow User.php model.
app/User.php
namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
app/Admin.php
namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
class Admin extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Step 3: Create Route and Controller
Ok, in this step we will create route for multi auth example for user and admin. so first add bellow route on routes.php file:
app/Http/routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('web-login', 'AuthAuthController@webLogin');
Route::post('web-login', ['as'=>'web-login','uses'=>'AuthAuthController@webLoginPost']);
Route::get('admin-login', 'AdminAuthAuthController@adminLogin');
Route::post('admin-login', ['as'=>'admin-login','uses'=>'AdminAuthAuthController@adminLoginPost']);
});
Add bellow code on Auth/AuthController.php file and put bellow code.
app/Http/Controller/Auth/AuthController.php
namespace AppHttpControllersAuth;
use AppUser;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
use IlluminateHttpRequest;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
/**
* 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 IlluminateContractsValidationValidator
*/
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']),
]);
}
public function webLogin()
{
return view('webLogin');
}
public function webLoginPost(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{
return back()->with('error','your username and password are wrong.');
}
}
}
Create new folder and AdminAuth and add new AuthController.php folder, put bellow code on that file.
app/Http/Controller/AdminAuth/AuthController.php
namespace AppHttpControllersAdminAuth;
use AppAdmin;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
use IlluminateHttpRequest;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
/**
* 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 IlluminateContractsValidationValidator
*/
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 Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function adminLogin()
{
return view('adminLogin');
}
public function adminLoginPost(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (auth()->guard('admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')]))
{
$user = auth()->guard('admin')->user();
dd($user);
}else{
return back()->with('error','your username and password are wrong.');
}
}
}
Step 4: Create Blade
In last step we have to create just two view for login user and other for login admin so let’s create file webLogin.blade.php file and put bellow code:
resources/views/webLogin.blade.php
@extends('layouts.app')
@section('content')
<div >
<div >
<div >
<div >
<div >Login</div>
<div >
<form role="form" method="POST" action="{{ route('web-login') }}">
{!! csrf_field() !!}
<div >
<label >E-Mail Address</label>
<div >
<input type="email" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span >
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div >
<label >Password</label>
<div >
<input type="password" name="password">
@if ($errors->has('password'))
<span >
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div >
<div >
<button type="submit" >
<i ></i>Login
</button>
<a href="{{ url('/password/reset') }}">Forgot Your Password?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Ok and also create other file for admin login.
resources/views/adminLogin.blade.php
@extends('layouts.app')
@section('content')
<div >
<div >
<div >
<div >
<div >Login</div>
<div >
<form role="form" method="POST" action="{{ route('admin-login') }}">
{!! csrf_field() !!}
<div >
<label >E-Mail Address</label>
<div >
<input type="email" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span >
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div >
<label >Password</label>
<div >
<input type="password" name="password">
@if ($errors->has('password'))
<span >
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div >
<div >
<button type="submit" >
<i ></i>Login
</button>
<a href="{{ url('/password/reset') }}">Forgot Your Password?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Now lets try and see…
Hope this code and post will helped you for implement Laravel 5.2 multi auth example using Auth guard from scratch. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs