Search code examples
phplaravelauthorizationlaravel-5.3

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?


Solution

  • 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,
    ];