iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
自我挑戰組

後端新手PHP+Laravel筆記系列 第 29

[Day29]Laravel Middleware

  • 分享至 

  • xImage
  •  

定義中間件

請使用Artisan 命令:make:middleware

php artisan make:middleware CheckWord
今天來做可以過濾不好字眼產品名稱的中間件
將要處理的邏輯放在hadle函數中

public function handle(Request $request, Closure $next)
{
    $checkwords = [ // 隨便舉個範例
        'cool',
        'wow'
    ];
    $parameters = $request->all();
    foreach($parameters as $key => $value){
        if ($key == "name"){
            foreach($checkwords as $checkword){
                if (strpos($checkword, $value) !== false){
                    return response('請重新輸入', 400);
                }
            }
        }
    }
    return $next($request);
}

註冊中間件

如果您希望在對您的應用程序的每個 HTTP 請求期間運行中間件,只需在app/Http/Kernel.php中列出你的$middleware類,只需將其附加到此列表並為其分配您選擇的鍵。

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    
    'check.word' => \App\Http\Middleware\CheckWord::class,
];

為路由分配中間件

Route::group(['middleware' => ['check.word']], function () {
    Route::resource('/product', 'productController');
});

測試

https://ithelp.ithome.com.tw/upload/images/20210927/20128999Pxj9RqH4ta.jpg

成功!!!!


上一篇
[Day28]Laravel Eloquent ORM
下一篇
[Day30]頒發和註銷訪問token
系列文
後端新手PHP+Laravel筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言