Installed Laravel sanctum but faced an error during creating token

Posted by

Error:

In sanctum.php line 21:

  Class "Laravel\Sanctum\Sanctum" not found 

Solution

Step 1: Install Sanctum

First, ensure that Sanctum is installed via Composer. Run the following command in your project directory:

composer require laravel/sanctum

Step 2: Publish Sanctum Configuration

If Sanctum is installed correctly but you are still seeing this error, ensure that the Sanctum configuration is published. Run:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

This will publish the Sanctum configuration file (sanctum.php) to the config directory.

Step 3: Run Migrations

Sanctum requires some tables to be created in the database. Run the migrations with the following command:

php artisan migrate

Step 4: Register Sanctum Middleware

Ensure that Sanctum middleware is added to the api middleware group in app/Http/Kernel.php. The middleware should look like this:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Step 5: Clear Configuration Cache

Sometimes, cached configurations can cause issues. To clear the cache, run the following command:

php artisan config:cache

Step 6: Verify Composer Autoload

If you have completed all the above steps and the issue persists, try regenerating the Composer autoload files:

composer dump-autoload

Step 7: Restart the Server

After completing the above steps, restart the Laravel development server:

php artisan serve

This should resolve the error. If the issue still persists, please make sure your Laravel version is compatible with Sanctum and that the composer.json file has the correct dependencies.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x