LogOut, destroy session in Laravel Sanctum together with Vue

- Andrés Cruz

En español
LogOut, destroy session in Laravel Sanctum together with Vue

Previously, we saw how to handle login and token usage via Cookies using Vue; all this, to master the use of Laravel Sanctum applied to the protection of a Rest Api consumed from Vue.

As part of the process, it is necessary to be able to destroy the session, so we will use the following implementation to do this.

To implement the logout option in the application, we will create a function that is responsible for eliminating the session:

app\Http\Controllers\Api\UserController.php

public function logout()
{
    session()->flush();
    return response()->json("Ok");
}

We create the route:

routes\api.php

Route::post('user/logout', [UserController::class, 'logout']);

We create a button to close the session, which we will place in the parent component, so that it can be automatically reused in the child components:

resources\js\vue\App.vue

<template>
  <nav class="bg-white border-b border-gray-100" >
    <header>
      <div class="flex gap-3 bg-gray-200">
        <nav-item :to="{ name: 'index' }" title="Cursos" />
        <router-link :to="{ name: 'login' }">login</router-link>
        <router-link to="">register</router-link>
        <o-button variant="danger" @click="logout">Close sesion</o-button>
      </div>
    </header>
  </nav>
  <router-view></router-view>
</template>

And the script that implements the above function:

logout(e) {
  e.preventDefault();
  this.$axios
    .post("/api/user/logout")
    .then(() => {
      window.location.href = "/vue";
    })
    .catch(function () {
      window.location.href = "/vue";
    });
},

As you can see, when making the HTTP request, we redirect to the root of the application, we use JavaScript primitives instead of SPA navigation to reload the whole page and with this, the access tokens; You could also use the logout function that is defined when installing Laravel Breeze:

this.$axios.post("/logout")

Since, in the end, what we do is destroy the session from Laravel.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.