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

Lars-Janssen's avatar

Laravel & vue.js keep session

Hi,

I've got a component that looks like this:

<subscription :subscriptions="{{json_encode($subscriptions)}}"></subscription>

Now I would like to make a post request within that component. I'm doing that like this:

methods: {
    unSubscribe(subscription) {
        MessageService.unSubscribe(subscription)
            .then(() => {
                this.subscriptions = this.subscriptions.filter((item) => subscription.id != item.id );
            });
    }
}
 unSubscribe (message) {
        return axios.post('/api/message/' + message.slug + '/unsubscribe');
    },

But when I dd() the authenticated user in api.php:

Route::group(['middleware' => ['auth:api']], function () {
    Route::post('/message/{message}/unsubscribe', function() {
        dd(Auth::user());
    });
});

In my bootstrap.js I've got:

I receive null?

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

How should I handle this?

0 likes
7 replies
Lars-Janssen's avatar

@cedamorim I've done that. The tokens in my get request look like this:

X-CSRF-TOKEN:0G6pkGWWJxFCeLOKp67mX3XQmUYakOyZIjXZZ1pe
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI6InVncko2SW1Ja3RMcU94SlZuNUtIdHc9PSIsInZhbHVlIjoicFFnak04T1wvR1pjTklQeVFrbFZvRmhpeFVoZXRkNzFEcHN2XC9Kaks1UE03Sm80ZklXaFBQcHNLbitRb0N2UVBEXC9NckNZMHNTT3NPaFNhdm15NFVtamc9PSIsIm1hYyI6ImI2NGM5NDRhZjkxMWZmYWQ5NTg0Y2VhNDY3MmE0MzU1ZjhkOGRmNDAzZmU4ZGYyMzJlNmM2YzQ5ZmI3YjAwZDMifQ==

But I get this back:

{error: "Unauthenticated."}
error
:
"Unauthenticated."
peterlc's avatar

I to got some problem going through the /api/ route. As you can see in Kernel.php the api middlewareGroup is quite different from the web one.

I read somewhere that the Laravel /api/ route is only for "external" api request and one should use the /web/ route for internal api connections.

Might be totally off but my problem disappeared.

cedamorim's avatar
Level 15

Yes, I understand. It's pretty annoying to get this straight. But let's try

In your "config/auth.php", in

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

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

In 'driver' => 'token', have you switched to 'passport'?

'api' => [
        'driver' => 'passport',
        'provider' => 'users',
]

From what I'm seeing, or might be this, or missing the middleware \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class in your App\Http\Kernel.php

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

See more here https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript

1 like

Please or to participate in this conversation.