0%

PHP Laravel 系列 - (15) 如何建立Middleware

1. 建立middleware

1
php artisan make:middleware CheckDirtyWord

路徑

1
app/http/Middleware

底下會多出一個CheckDirtyWord.php

image-20220110132249158

2. 撰寫dirtyword檢查

打開 CheckDirtyWord.php 我們會看到有一個function 名稱為handle,試著改成以下的程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public function handle(Request $request, Closure $next)
{
$dirtyWords = [
'apple',
'orange'
];

$parameters = $request->all();

foreach($parameters as $key => $value){
if($key == 'content'){
foreach($dirtyWords as $dirtyWord){
if(strpos($value,$dirtyWord) !== false){
return response('dirty!',400);
}
}
}
}

return $next($request);

}

3. kernel.php 加上middleware

$routeMiddleware加上一個,名稱可以自己取:

1
'check.kite' => \App\Http\Middleware\CheckDirtyWord::class,

如下:

1
2
3
4
5
6
7
8
9
10
11
12
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.kite' => \App\Http\Middleware\CheckDirtyWord::class,
];

4. 修改router

1
2
3
Route::group(['middleware' =>'check.kite'],function(){
Route::resource('main','MainController');
});

5. POSTMAN 測試

1
http://127.0.0.1:8000/main

image-20220110133608558