试图将一条路由分配给多个中间件

时间:2020-04-30 21:18:06

标签: laravel

将一个路由分配给多个中间件时遇到问题 这就是我在web.php中所拥有的

    Route::group(['middleware' => ['hodAndProvost']], function () {
    Route::match(['post','get'],'applied', 'LeavesController@applied');
    Route::match(['post','get'],'approval/{id}', 'LeavesController@approval');
});

这是我在App \ htpp \ kanel.php中拥有的

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'hodAndProvost' => [
        \App\Http\Middleware\hodMiddleware::class,
        \App\Http\Middleware\provostMiddleware::class,
    ],

    'application' => [
        \App\Http\Middleware\hodMiddleware::class,
        \App\Http\Middleware\provostMiddleware::class,
        \App\Http\Middleware\lecturerMiddleware::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

这是我在hodMiddleware中拥有的

public function handle($request, Closure $next)
{
    if ($request->user() && $request->user()->user_access_id != '2')
{
    return new Response(view('unauthorized')->with('role', 'HOD'));
}
    return $next($request);
}

这是我在provostMiddleware中拥有的

public function handle($request, Closure $next)
{
    if ($request->user() && $request->user()->user_access_id != '3')
{
    return new Response(view('unauthorized')->with('role', 'PROVOST'));
}
    return $next($request);
}

这是我得到的错误

Symfony \ Component \ Debug \ Exception \ FatalThrowableError

找不到“ App \ Http \ Middleware \ Response”类

1 个答案:

答案 0 :(得分:1)

您没有导入Response类,因此为什么要在同一名称空间中寻找它。您甚至还不需要创建新的Responseview()也是一种响应。

尝试以下代码:

<?php

namespace App\Http\Middleware;

use Closure;

class hodMiddleware
{
    public function handle($request, Closure $next)
    {
        if ($request->user() && $request->user()->user_access_id != 2) {
            return view('unauthorized')->with('role', 'HOD'); // like your example
            // OR: //
            return redirect()->back();
        }

        return $next($request);
    }
}

关闭主题,但始终使用大写字母开头课程名称。 :)