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:


public function logout()
    return response()->json("Ok");

We create the route:


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:


  <nav class="bg-white border-b border-gray-100" >
      <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>

And the script that implements the above function:

logout(e) {
    .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:


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

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.