Laravel 框架已經內建一些中介層,包括維護、身份驗證、CSRF 保護,等等。所有的中介層都位於 app/Http/Middleware 目錄內
一、建立一個中介層
php artisan make:middleware OldMiddleware
此指令將會 在 app/Http/Middleware 目錄內建立一個名稱為 OldMiddleware 的類別
//以下中介層,$request->age不大於200即轉走!
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
}
二、有些事可以在haddle之前先做 之前
<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// Perform action
return $next($request);
}
}
之後
<?php
namespace App\Http\Middleware;
use Closure;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
}
三、註冊全域:只要將中介層的類別加入到 app/Http/Kernel.php 的 $middleware 屬性清單列表中。
指派給路由:
1.先在Kernel.php指定key
如:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
你即可在設定路由時使用
Route::get('admin/profile', function () {
//
})->middleware('auth');
沒有留言:
張貼留言