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