Fixing ReflectionException: Class scope does not exist in file when setting up Laravel Passport Scopes

Problem: I’m retro-fitting ‘scopes’ to an existing Laravel Passport API to allow some different levels of client access. After adding the available scopes with Passport::tokensCan, and default scopes with Passport::setDefaultScope, and attempting to specify a scope on a route like so:

Passport::setDefaultScope([
    'other-access'
]);

Passport::tokensCan([
    'write-access' => 'Read-write access',
    'read-access' => 'Read-only access',
    'other-access' => 'Other access'
]);
Route::get('endpoint/count', 'API\EndpointController@count')->middleware(['auth:api', 'scope:read-access']);

And an attempt to query the route gives this error:

ReflectionException: Class scope does not exist in file /path/to/webroot/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 790

Solution: READ THE DOCS. Again, I didn’t read the docs FULLY. In order to use token scopes, the docs say…

To get started, add the following middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

🤦🏻‍♂️ 🤦🏻‍♂️ 🤦🏻‍♂️ 🤦🏻‍♂️ 🤦🏻‍♂️ 🤦🏻‍♂️

Leave a Reply

Your email address will not be published. Required fields are marked *