Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Eloïse's avatar

Error 500 on api calls after installing sanctum

Hello, I'm using sanctum and fortify in my project, I've followed the installation instructions but unfortunately I got an error 500 now (I've tested the api before)

config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


//Api routes are sanctum's auth protected (need a user bearer token)
Route::group(['middleware' => ['auth:sanctum']],function (){

    Route::apiResource('/stage','App\Http\Controllers\Api\StageController');

});

config/sanctum.php

//'guard' => ['web'],
    'guard' => ['api'],

Do you see where is my mistake ? best regards.

0 likes
2 replies
LaryAI's avatar
Level 58

The error 500 could be caused by a variety of issues. Here are a few things to check:

  1. Make sure you have run the migration for Sanctum: php artisan migrate

  2. Check that you have added the CreateFreshApiToken middleware to your web middleware group in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // ...
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \App\Http\Middleware\CreateFreshApiToken::class,
        ],
    ];
    
  3. Make sure you are sending the X-XSRF-TOKEN cookie with your requests. This cookie is used by Sanctum to verify that the request is coming from a trusted source. You can add this cookie to your requests using JavaScript:

    axios.defaults.xsrfCookieName = 'XSRF-TOKEN';
    axios.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
    
  4. Check your server logs for any error messages that might give you more information about the issue.

If none of these solutions work, try commenting out the auth:sanctum middleware on your routes and see if you can access them without authentication. If you can, then the issue is likely with your authentication setup. If you still get an error 500, then the issue might be with your code or server configuration.

Eloïse's avatar
Eloïse
OP
Best Answer
Level 2

OK, after changing config/sanctum back to

'guard' => ['web'],

and cache:clear it works. Somebody can explain me why I should not change sanctum's config file to 'guard' => ['api'] ?

Please or to participate in this conversation.