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

floreap's avatar

Laravel Vue Sanctum Unauthenticated

api.php

<?php
  
use App\Http\Controllers\PostController;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
  
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware(Authenticate::using('sanctum'));

Route::post('posts', [PostController::class, 'store'])->middleware(Authenticate::using('sanctum'));

When I call the http:/localhost:8000/api/posts inside Vue with axios I get 401 Unauthorized and response {"message":"Unauthenticated."}.

I used Laravel Breeze in the setup.

0 likes
3 replies
omeratayilmaz's avatar
Level 13

You are sending requests to posts, and the Sanctum middleware is running. Are you sure about the logic?

Because it works as expected. If you want to access posts regardless of authentication, just use:

Route::post('posts', [PostController::class, 'store']);

Because with the current code, Sanctum checks for a token

1 like
omeratayilmaz's avatar

Additionally, if you want to use Sanctum middleware for authentication, you can do it like this:

Route::middleware('auth:sanctum')->post('posts', [PostController::class, 'store']);
1 like
floreap's avatar

@omeratayilmaz Made it work finally.

I moved the route inside web.php and used

Route::post('posts', [PostController::class, 'store']);

Then there was CSRF token mismatch which I solved it by calling

axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});
1 like

Please or to participate in this conversation.