[Vuejs]-Load current user with Vue/Axios in Laravel

2👍

Your user computed property returns Promise object not desired value.

Below is my proposition of solving your problem. You should be able to succesfully call @{{ user }} within your blade files. However to access user property in children components you are forced to use $parent.user property of theirs.

Personally I recommend you checking out Vuex which is made for such cases. It is centralized state storing solution allowing you to access (and manage) data from all over your app.

new Vue({
  el: '#app',
  data () {
    return {
      user: null
    };
  },
  created () {
    // As app intializes user is fetched and saved
    this.fetchUser();
  },
  methods: {
    fetchUser () {
      axios.get('/current-user')
        .then(response => {
          this.user = response.data;
        })
        .catch(error => {
          alert('Something went wrong');
          console.error(error.response.data);
        });
    }
  },
  router
});

Leave a comment