简体   繁体   中英

Laravel Auth Middleware: Class can does not exist

I'm trying to protect a route via middleware as described in the doc

When I hit the url, I get:

ReflectionException in Container.php line 749:
Class can does not exist

Here's the relevant part from routes.php :

Route::get('{user}/profile/edit/{type?}', [
    'as'   => 'edit',
    'uses' => 'User\UserController@edit',
    'middleware' => ['can:edit-user,user'],
]);

AuthServiceProvider.php :

public function boot()
{
    $this->registerPolicies();

    // ... other definitions

    Gate::define('edit-user', function ($user, $subjectUser) {
        return
            $user->hasRole('manage.user') // if the user has this role, green
            ||
            ($user->isAdmin && $user->id == $subjectUser->id) // otherwise if is admin, can edit her own profile
            ;
    });

Maybe it's because I'm not using a separate policy class for defining the gate?

According to the documentation on using Middleware with Routes - you need to register the definition in app/Http/Kernel.php

If you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

The error you're seeing shows that this definition is missing. You need to add something like;

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    //...
    'can' => \Path\To\Your\Middleware::class,
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM