Laravel Sanctum - Logged in user best practise Laravel Sanctum - Logged in user best practise laravel laravel

Laravel Sanctum - Logged in user best practise


Using Vue and Vuex for my SPA, I have managed to keep track of authenticated users using the setup below:

store.js

The store.js keeps track of the user and isLoggedIn state.

import { isLoggedIn } from "./utils";export default {    state: {        isLoggedIn: false,        user: {}    },    mutations: {        setUser(state, payload) {            state.user = payload;        },        setLoggedIn(state, payload) {            state.isLoggedIn = payload;        }    },    actions: {        async loadUser({ commit, dispatch }) {            if (isLoggedIn) {                try {                    const user = (await axios.get("/user")).data;                    commit("setUser", user);                    commit("setLoggedIn", true);                } catch (error) {                    console.log(error)                }            }        }    }};

utils.js

The utils.js contains helpers for setting and getting logged in state from local storage.

  export function isLoggedIn() {    return localStorage.getItem("isLoggedIn") == "true";}export function logIn() {    localStorage.setItem("isLoggedIn", true);}

Login.vue

In the login.vue, i'm calling the logIn() from the utils.js to set the isLoggedIn value in LocalStorage.

Also, the loadUser action is being dispatched to set the user information in the Vuex store.

<script>import { logIn } from "../utils"; methods: {        async login() {            try {                await axios.get("/sanctum/csrf-cookie");                await axios.post("/login", {                    email: this.email,                    password: this.password                });                logIn();                this.$store.dispatch("loadUser");                this.$router.push('/');            } catch (error) {                console.log(error);            }        }    }</script>

App.js

The loadUser action is also being dispatched here to make the user's information available globally if logged in.

const app = new Vue({    ...    async beforeCreate() {        this.$store.dispatch("loadUser");    }});


store it in sessionStorage, and also initialize loggedInUser from sessionStorage as:

sessionStorage.getItem('loggedInUser') === 'true' || false