我用这段代码创建了一个 Laravel 中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Containers\Modals\Models\Modal;
class ModalsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string $modalNames): Response
{
$modals = explode(',', $modalNames);
foreach ($modals as $modalName) {
$modal = Modal::where('slug', $modalName)->first();
if (!$modal->enabled) {
abort(404);
}
}
return $next($request);
}
}
然后我更新了
Kernel.php
:
**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
...,
'modals' => \App\Http\Middleware\ModalsMiddleware::class,
];
对于我的路线组,我添加了以下内容:
Route::group([
'prefix' => 'api/v1/routeName',
'middleware' => ['auth:api', 'modals:AModalName']
], function() {...});
然后我跑了:
php artisan optimize && php artisan config:cache && php artisan cache:clear && php artisan config:clear && composer dump-autoload
然后停止服务然后我重新运行应用程序
但是我遇到了这个错误:
"message": "Target class [modals] does not exist.",
"exception": "Illuminate\\Contracts\\Container\\BindingResolutionException",
我该如何解决这个问题?
在 Larave 11 中,您必须在
bootstrap/app.php
文件中注册中间件。
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'modals' => \App\Http\Middleware\ModalsMiddleware::class,
]);
})
更多详情请访问官方文档。