Middleware 是個很實用的功能,小弟主要都用這個功能處理一些用戶特殊權限的處理,像是用戶對於此頁面的時間進去的權限或者是一些有關sub-domain的權限檢查。
php artisan make:middleware myMiddleware
protected $routeMiddleware = [
...
'myMiddleware'=> \App\Http\Middleware\myMiddleware::class,
...
];
Route::group([ 'prefix' => 'admin' , 'middleware' => 'myMiddleware:admin' ], function () {
Route::post('/blog/create', "BlogController@create" )->name( 'Blog_create');
......
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class myMiddleware
{
private $modUser;
function __construct(){
$this->modUser = new \App\mod_userBase();
}
public function handle($request, Closure $next ,$role = "-1")
{
// 1. 檢查用戶資訊
if (!(Auth::guard('admin')->check()) ) {
return redirect()->route("admin.auth.logout");
}
$AuthData = Auth::guard('admin')->user() ;
// 2. 檢查用戶是否啓用
// 3. 檢查....
return $next($request);
}
}
對於從codeigniter換到 laravel 有時會覺得Middleware 不太習慣,不過用久了反而覺得還蠻不錯用的。