實施自定義中間件:
Laravel的中間件提供了一種有力的機制,用於過濾HTTP請求輸入您的應用程序。創建自定義中間件使您可以將自己的邏輯註入請求生命週期。這是逐步指南:
php artisan make:middleware CheckAge
。這將在app/Http/Middleware/CheckAge.php
中創建一個新的中間件文件。handle
方法中,您將放置自定義邏輯。此方法收到請求( $request
)和關閉( $next
)。閉合代表下一個中間件或路由處理程序。例子:<code class="php"><?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAge { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle(Request $request, Closure $next) { if ($request->age </code>
app/Http/Kernel.php
中註冊新創建的中間件。將其添加到$routeMiddleware
數組:<code class="php">protected $routeMiddleware = [ // ... other middleware ... 'checkage' => \App\Http\Middleware\CheckAge::class, ];</code>
routes/web.php
或routes/api.php
文件中的特定路由或一組路由:<code class="php">Route::get('/profile', [ProfileController::class, 'show'])->middleware('checkage');</code>
實施自定義過濾器(注意:Laravel的術語通常使用“中間件”而不是“過濾器”):
儘管Laravel並沒有像某些較舊的框架那樣明確使用術語“過濾器”,但中間件有效地具有相同的目的。上面的代碼示例通過檢查年齡並重定向到未達到條件,證明了類似濾波器的行為。中間件中的handle
方法充當過濾器功能。
handle
方法中創建它們。這可以提高可檢驗性和可維護性。 Laravel提供了用於身份驗證( auth
)和授權( auth.basic
, can
等)的內置中間件。您可以直接使用這些或創建自定義中間件來擴展或自定義身份驗證/授權邏輯。
使用內置中間件的示例:
<code class="php">Route::get('/profile', [ProfileController::class, 'show'])->middleware('auth'); //Requires authentication Route::get('/admin', [AdminController::class, 'index'])->middleware('auth', 'admin'); //Requires authentication and admin role (assuming you have an 'admin' middleware defined)</code>
自定義授權中間件的示例:
<code class="php"><?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class CheckAdmin { public function handle(Request $request, Closure $next) { if (Auth::check() && Auth::user()->isAdmin()) { return $next($request); } abort(403, 'Unauthorized'); // Return 403 Forbidden if not an admin } }</code>
請記住在您的app/Http/Kernel.php
文件中註冊此CheckAdmin
中間件。
try...catch
塊優雅地管理錯誤。app/Http/Kernel.php
的$routeMiddleware
陣列中正確註冊自定義中間件。一個常見的錯誤是忘記此步驟,使中間件無效。以上是如何在Laravel應用程序中實現自定義中間件和過濾器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!