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

patressz's avatar

Auth sanctum question

Hi guys, I'm using laravel/breeze starter kit for registration and login and I have an API endpoint in routes/api.php:

// routes/api.php
Route::apiResource('locations', LocationController::class)->only('index');

i need to publish this endpoint only for logged in users, i add auth:sanctum middleware for my route:

// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('locations', LocationController::class)->only('index');
});

then when i'm logged in i send an ajax request to that route to get the locations. A My question is: is this a good way to protect my api endpoints within cookie-based authentication? or is there something wrong with my code?

i don't create a personal acces token when logging in.

Thank you so much :)

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, using the auth:sanctum middleware to protect your API endpoints is a good way to ensure that only authenticated users can access them. This middleware will check if the user making the request has a valid session cookie or token, and if not, it will return a 401 Unauthorized response.

If you are using Laravel Breeze, it already includes Sanctum and sets up the necessary middleware for you. So, you don't need to create a personal access token manually.

Your code looks good, and you are using the middleware correctly. Just make sure that you are sending the session cookie or token with your AJAX requests, so that the middleware can authenticate the user.

Here's an example of how you can send the session cookie with an AJAX request using jQuery:

$.ajax({
    url: '/api/locations',
    type: 'GET',
    dataType: 'json',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-XSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
    },
    success: function(response) {
        console.log(response);
    },
    error: function(xhr) {
        console.log(xhr.responseText);
    }
});

Note that we are setting the X-XSRF-TOKEN header with the value of the CSRF token, which is required for Laravel to verify the authenticity of the request. You can get the CSRF token value from a meta tag in your HTML:

<meta name="csrf-token" content="{{ csrf_token() }}">

Please or to participate in this conversation.