參考官方網站安裝 Laravel 8.x
composer global require laravel/installer
laravel new example-app
# 直接安裝最新版
composer create-project laravel/laravel example-app
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
建立 Admin 資料表、模型
php artisan make:model Admin -mfs
app\Models\Admin.php (Laravel 8.x 預設將模型檔案放置 app\Models 目錄下)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
app\Database\migration\[時間序]_create_admins_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
修改 config/auth.php
'guards' => [
//前台使用者
'web' => [
'driver' => 'session',
'provider' => 'users',
],
//後台管理者
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
//使用users資料表
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
//使用admins資料表
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
建立 Admin 登入登出控制器
php artisan make:controller Auth\AdminLoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
class AdminLoginController extends Controller
{
//先經過 middleware
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
//顯示 admin.login 視圖
public function showLoginForm()
{
return view('admin.login');
}
//登入
public function login(Request $request)
{
// 驗證表單資料
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4'
]);
// 將表單資料送去驗證
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
//驗證無誤轉入 admin.dashboard
return redirect()->intended(route('admin.dashboard'));
}
// 驗證失敗 返回並拋出表單內容 只拋出 email 與 remember 欄位資料
return redirect()->back()->withInput($request->only('email', 'remember'));
}
//登出
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/admin');
}
}
修改 Middleware\RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
//當使用者被確認後,判斷是前台還是後台來的使用者並轉到正確的頁面位置
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
default:
if (Auth::guard($guard)->check()) {
return redirect('/');
}
break;
}
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
}
return $next($request);
}
}
建立後臺資訊看板控制器
php artisan make:controller Admin\AdminDashboardController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use View;
class AdminDashboardController extends Controller
{
/**
* Create a new controller instance.
* 進到這個控制器需要透過middleware檢驗是否為後台的使用者
* @return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* 顯示 dashboard.
* 並將 使用者的資料拋出
* @return \Illuminate\Http\Response
*/
public function dashboard()
{
$adminuser = Auth::user();
return View::make('admin.dashboard', compact('adminuser'));
}
}
新增後台管理者 Login 表單及 Dashboard 測試頁面
login.blade.php
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin=anonymous>
<title>Admin</title>
</head>
<body>
<div>
<div>
<div>
<div>
<div>
<form id="sign_in_adm" method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<h1>Admin Login</h1>
<div>
<input type=email name=email placeholder="Email Address" value="{{ old('email') }}" required autofocus>
</div>
@if ($errors->has('email'))
<span><strong>{{ $errors->first('email') }}</strong></span>
@endif
<br>
<div>
<input type=password name=password placeholder="Password" required>
</div>
<br>
<div>
<button type=submit>SIGN IN</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
dashboard.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin=anonymous>
<title>Admin Dashboard</title>
</head>
<body>
<div>
<div>
<div></div>
<div>
<div>
<div>
<h1>Welcome To Admin Dashboard</h1>
</div>
</div>
<br><br>
登入帳號: {{ $adminuser->email }}
<br><br>
<a href="/admin/logout">Logout</a>
</div>
<div></div>
</div>
</div>
</body>
</html>
修改 routes\web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//前台 web 用的路由 網址看起來就像 https://localhost/{名稱}
use App\Http\Controllers\HomeController;
Auth::routes(); //內建 Auth 路由
Route::get('/', [HomeController::class, 'welcome']);
Route::get('/home', [HomeController::class, 'index'])->name('home');
//後台 admin 用的路由 網址看起來就像 https://localhost/admin/{名稱}
use App\Http\Controllers\Auth\AdminLoginController;
use App\Http\Controllers\Admin\AdminDashboardController;
Route::prefix('admin')->group(function() {
Route::get('/', [AdminLoginController::class, 'showLoginForm'])->name('admin');
Route::get('/login', [AdminLoginController::class, 'showLoginForm'])->name('admin.login');
Route::post('/login', [AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::get('/logout', [AdminLoginController::class, 'logout'])->name('admin.logout');
Route::get('/dashboard', [AdminDashboardController::class, 'dashboard'])->name('admin.dashboard');
}) ;