Laravel 5.6自定义中间件破坏模型绑定

时间:2018-08-29 20:39:26

标签: php laravel eloquent middleware laravel-5.6

这是我的routes/api.php

Route::group([
    'middleware' => 'jwt.auth',
], function ($router) {

    //Route group with my custom middleware
    Route::group([
        'middleware' => CheckPermission::class
    ], function ($router) {

        Route::group([
            'prefix' => 'permissions'
        ], function($router) {

            Route::resources([
                'users' => 'UserPermissionController'
            ]);
        });

    });

});

这是我要使用的控制器方法:

public function update(Request $request, User $user)
{
    dd($user);
}

编辑: 我的CheckPermission中间件:

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Auth;

use Illuminate\Routing\Router;

use App\MethodModuleUser;

class CheckPermission
{

    protected $router;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $method = $request->method();
        $path = $this->router->getRoutes()->match($request)->uri;
        $path = str_replace('api/', '', $path);

        $permissions = MethodModuleUser::with([
            'user',
            'module',
            'method'
        ])->whereHas('user', function($query) {
            $query->where('id', Auth::id());
        })->whereHas('module', function($query) use ($path) {
            $query->where('url', $path);
        })->whereHas('method', function($query) use ($method) {
            $query->where('name', strtoupper($method));
        })->count();

        if($permissions <= 0) {
            return response()->json([
                'message' => 'No tiene los privilegios para realizar esta acción'
            ], 403);
        }

        return $next($request);
    }
}

当我使用自定义中间件时,模型绑定不起作用,$user只是一个空模型,但是当我注释'middleware' => CheckPermission::class行时,模型绑定就可以正常工作。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

我相信这是因为您需要使用在app\Http\Kernel.php中为中间件创建的别名。

 protected $routeMiddleware = [
        ...
        'checkPermissions' => CheckPermissions::class,

(如果需要,请不要忘记使用import语句)

然后在您的路线中使用;

'middleware' => 'checkPermissions'

答案 1 :(得分:0)

好的,我不知道这是否是个好习惯,但我已解决。如果有人也有此问题,我会发布解决方案:

spark.sql("set spark.sql.caseSensitive=true") 中间件中,我这样调用CheckPermission中间件来替换return $next($request)

SubstituteBindings

编辑:

解决此问题的另一种方法是在return app(\Illuminate\Routing\Middleware\SubstituteBindings::class) ->handle($request, function($request) use ($next) { return $next($request); }); 中间件中使用$request->route()->uri,而不是像Ross Wilson在评论中所说的那样,在CheckPermission中找到它。现在不再需要Router和调用__construct(Router $router)中间件。