W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
要建立一個新的中間件,可以使用 make:middleware 這個 Artisan 命令:
php artisan make:middleware OldMiddleware
此命令將會 在 app/Http/Middleware 目錄內(nèi)置立一個名稱為 OldMiddleware 的類。在這個中間件內(nèi)我們只允許 年齡 大于 200 的才能訪問路由,否則,我們會將用戶重新導(dǎo)向 「home」 的 URI 。
<?php namespace App\Http\Middleware;
class OldMiddleware {
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('age') < 200)
{
return redirect('home');
}
return $next($request);
}
}
如你所見,若是 年齡 小于 200 ,中間件將會返回 HTTP 重定向給客戶端,否則,請求將會進一步傳遞到應(yīng)用程序。只需調(diào)用帶有 $request 的 $next 方法,即可將請求傳遞到更深層的應(yīng)用程序(允許跳過中間件) HTTP 請求在實際碰觸到應(yīng)用程序之前,最好是可以層層通過許多中間件,每一層都可以對請求進行檢查,甚至是完全拒絕請求。
Before / After 中間件
在一個請求前后指定某個中間件取決于這個中間件自身。這個中間件可以執(zhí)行在請求前執(zhí)行一些 前置 操作:
<?php namespace App\Http\Middleware;
class BeforeMiddleware implements Middleware {
public function handle($request, Closure $next)
{
// Perform action
return $next($request);
}
}
然后,這個中間件也可以在請求后執(zhí)行一些 后置 操作:
<?php namespace App\Http\Middleware;
class AfterMiddleware implements Middleware {
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: