Optimal method for managing user session data in Vue with the power of Laravel and Inertia

I am creating an application that features a dynamic menu using Laravel, Vue, and Inertia.

To transmit the session details about the menu items to be displayed (such as icons) and user information (like avatar and name), I currently rely on the HandleInertiaRequests middleware.

However, sending all this data with every Inertia request doesn't seem like the most efficient solution in my opinion.

Is there a way to optimize this process by delivering the session information just once, ideally during the login phase?

Answer №1

When dealing with storing user details in vuex from MasterLayout.vue, it is important to ensure that the layout is only mounted after the user has logged in.

Within the MasterLayout.vue component;

<template>
  ...
</template>

<script>
...
mounted() {
 this.$store.dispatch("setUser");
}
</script>

Next, within the auth.js file;

export const auth = {
state: () => ({
    user: [],
}),

actions: {
    setUser({ commit }) {
        commit("SET_USER");
    },
},

mutations: {
    async SET_USER(state) {
        await axios
            .get(route("user"))
            .then((response) => {
                state.user = response.data;
            })
            .catch((error) => {
                console.log(error);
            });
    },
},

getters: {
    auth(state) {
        return state.user;
    },
  },
};

Finally, in the Avatar.vue component;

  <template>
    //do anything with data
    {{auth.name}}
    {{auth.email}}
  </template>

  <script>
    computed: {
     ...mapGetters(["auth"]),
    },
  </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh information in Chart.js in Vue.js upon hitting the submit button

I am currently working on a vuejs chart that displays data, and I have been trying to update the labels but it doesn't seem to be working. Here's the code in ChartjsComponentLineChart.vue: <script> import { Line } from 'vue-chartjs&ap ...

Steps for launching a hyperlink in a browser on Vue Native

I'm having trouble finding information on how to properly use the Linking component in react-native. The resources available are limited, and I'm not sure if I am implementing it correctly... Below is what I have in my template: <nb-button :o ...

Encountering a syntax error or access violation problem when creating a new table migration in Laravel

Within my Laravel application, I have created the following table migration: <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schem ...

Utilize the same Apollo GraphQL query definition across various Vue components for different properties

On my vue screen, I am trying to utilize a single apollo graphql query that I have defined for two different properties. From what I understand, the property name must correspond with an attribute name in the returned json structure. I attempted to use the ...

Laravel and jQuery: Seamlessly Uploading Images with AJAX

I have been facing issues while trying to upload photos in Laravel using jQuery AJAX. I keep encountering an error message: The photo must meet the following criteria: - The photo must be an image. - The photo must be a file of type: jpeg, png, jpg, gif, ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Enable the normal back button functionality when new query parameters are added dynamically

Whenever a page is visited without any parameters, I push some parameters to the Nuxt router. This process can be seen in more detail at https://router.vuejs.org/guide/essentials/navigation.html. For example, if someone visits: /program, they will end up ...

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

Ways to update a PHP array

I have a simple inquiry without an answer yet. Is there a way to transform my array from this: [{"sku":"6"},{"buyers":"7"},{"base":"8"}] to this: [{"sku":"6","buyers":"7","base":"8"}] I am dealing with three queries for three separate database tables: ...

Is there a way to disable a Quasar q-input attribute when a button is clicked?

Looking for some help with a quasar q-input element - I want to be able to toggle its enable and disable state at the click of a button. I managed to add a button to the input using v-slot:after, but I am struggling to figure out how to remove the "disabl ...

How can Vue handle passing an array in this scenario?

In my code snippet, I am attempting to build a simple form builder application. The goal is to include multiple select fields in the form. I encountered a problem with passing an array into a loop. Despite my efforts, the code did not work as expected. Ho ...

Using Vue.js: Passing an object from data() to a mounted() function

I'm facing an issue while attempting to pass the grid array to the createGridChart. An error message stating "grid is not defined" keeps popping up: “grid is not defined”. export default { data() { return { grid: [], } ...

What is causing Vue to not update a list when using props?

When my App loads, I make an API call in the mounted() method to retrieve a JSON with a list of items. After that, I update the prop set in my target component Homepage: Homepage.pages = resJSON.data.pages; Take a look at the App code below: <template& ...

I am interested in checking the dates of the current date and disabling the button if the date falls within that range

I am attempting to deactivate a button if the current date falls within a three-month period. Despite my efforts to use a combination of Php and JavaScript, I was unable to make it work. PHP Code @php($found = false) @foreach($doctors as $doctor) ...

Struggling to properly send props to the child component in Vue 3

Is there a way to pass data from the request through axios in the root component to the child using Vue? Currently, only the "title" field is displayed correctly, but I also need to output the "body". Note: This is my first time working with Vue and I&apo ...

Vuex getter not reflecting changes in filter after modifying state array

I am currently working on a to-do application where I have implemented a button to toggle the checked/completed state of all todos. However, I have encountered an issue where although I am mutating an array of the state, the getters are not updating accord ...

What is the best way to ensure a PrimeVue TabPanel takes up the full vertical space and allows the content within the tabs to be scroll

I have created a sandbox demo to illustrate my issue. My goal is to make the content of tabs scroll when necessary but fill to the bottom if not needed. I believe using flex columns could be the solution, however, my attempts so far have been unsuccessful. ...

Organizing Vue.js components into separate files for a cleaner view model architecture

Having smooth functionality in a single file, I encountered difficulties when attempting to break up the code into multiple files and bundle it in a .vue file. Below is the final .vue file for simplicity. Here is the HTML file: <!DOCTYPE html> < ...

Utilize the @blur event within flatpickr to trigger actions when the output is empty

<b-col md="7" offset-md="1"> <b-form-group> <template> Date and Time <flat-pickr id="datetime" v-model="datetime" class="form-control" ...