Multiple authentication in Laravel 5.4
Chào mọi người, nhân tiện sự kiện Laravel release bản 5.5 mình xin được làm tutorial hướng dẫn về authentication trong Laravel 5.4 :D
Và sẽ hứa hẹn update phần này trong thời gian không xa tới.
Đi vào vấn đề chính
Tạo migration, model và seed dữ liệu cho admin
php artisan make:model Models/Admin
php artisan make:migration create_admins_table --create=admins
php artisan make:seeder AdminsTableSeeder
Migration cho admin
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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->string('password', 60);
$table->rememberToken();
$table->boolean('status')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Model Admin
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $table = 'admins';
}
Seed dữ liệu admin
<?php
use Illuminate\Database\Seeder;
use App\Models\Admin;
class AdminsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Admin::create([
'name' => 'Admin',
'email' => 'admin@haposoft.com',
'password' => Hash::make('haposoft'),
]);
}
}
Xong xuôi nhớ chạy db seed nhé bạn.
Tiếp tục chương trình bạn tạo các middleware cho phần login của admin
php artisan make:controller AdminAuth/AuthController
php artisan make:middleware Admin/Authenticate
php artisan make:middleware Admin/RedirectIfAuthenticated
php artisan make:controller Admin/DashboardController
Bạn edit lại AdminAuth/AuthController
<?php
namespace App\Http\Controllers\AdminAuth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/admin/dashboard/';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('admin_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:190',
'email' => 'required|email|max:190|unique:admins',
'password' => 'required|confirmed|min:8',
]);
}
public function showLoginForm()
{
return view('auth_admin.login');
}
protected function guard()
{
return Auth::guard('admin');
}
}
Authenticate
<?php
namespace App\Http\Middleware\Admin;
use Closure;
class Authenticate
{
/**
* 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)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('admin/login');
}
}
return $next($request);
}
}
RedirectIfAuthenticated
<?php
namespace App\Http\Middleware\Admin;
use Closure;
class RedirectIfAuthenticated
{
/**
* 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/dashboard/');
}
return $next($request);
}
}
DashboardController
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class DashboardController extends Controller
{
public function index()
{
return view('admin.index');
}
}
Thêm guards cho admin trong fie config/auth.php
//For Admin Module
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
add thêm providers
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
passwords
'admins' => [
'provider' => 'admins',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
Tạo file view cho login admin
auth_admin/login.blade.php
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form role="form" method="POST" action="{{ route('admin.login') }}">
{{ csrf_field() }}
<div class="form-group has-feedback">
<input id="email" type="email" name="email" class="form-control" placeholder="Email" value="{{ old('email') }}" required autofocus>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
<div class="form-group has-feedback">
<input type="password" id="password" type="password" class="form-control" name="password" placeholder="Password" required autofocus>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
<div class="row">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
</form>
</div>
route
Route::group(['namespace' => 'AdminAuth', 'prefix' => 'admin'], function () {
Route::get('login', 'AuthController@showLoginForm');
Route::post('login', ['as' => 'admin.login','uses' => 'AuthController@login']);
Route::get('logout', ['as' => 'admin.logout','uses' => 'AuthController@logout']);
});
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'as' => 'admin.','middleware' => 'admin_auth'] ,function() {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});
Và nhớ add thêm phần định nghĩa các Middleware vào Kernel.php
nhé
'admin_auth' => \App\Http\Middleware\Admin\Authenticate::class,
'admin_guest' => \App\Http\Middleware\Admin\RedirectIfAuthenticated::class,
Do thời gian có hạn tôi sẽ liên tục cập nhật tutorial này và giải thích chi tiết thêm những định nghĩa và thắc mắc tại đây ^^