How to get current authenticated user id using Vuejs and Laravel?

31,042

Solution 1

Other option is to do it the same way as the crsf token.

// header.blade.php
<meta name="user-id" content="{{ Auth::user()->id }}">

// main.js
Vue.prototype.$userId = document.querySelector("meta[name='user-id']").getAttribute('content');

// component

mounted() {
    console.log(this.$userId)
}

Solution 2

If you are using authentication created by the 
composer require laravel/ui
php artisan ui vue --auth

You can add to

// app.blade.php or whatever you have maybe master.blade.php
 @if (Auth::check()) 
         <meta name="user_id" content="{{ Auth::user()->id }}" />
 @endif 

Then in the app.js add
Vue.prototype.$userId = document.querySelector("meta[name='user_id']").getAttribute('content');


Now if you want to get the logged in  user id and pass it to a hidden input field the first declare it as 

<script>

export default {
        props: ['app'],
        data()
        {
            return{
                user_id: this.$userId,
            }
        },

    }
</script>

  // Finally in your MyVueComponent.vue
<input type="hidden" name="user_id" v-model="user_id">

To test try making the type="text" instead of "hidden" and you see that it is shows you the current id

Solution 3

I've needed to pass data to my Header component, so I thought I may share the way I'm doing it

<fronend-header :current-user="{{ json_encode(['isLoggedIn'=>auth()->check() ? true : false, 'user'=>auth()->check() ? auth()->user() : null]) }}" />

On the vuejs side

<script>
    export default {
        name: "frontend-header",

        props: {
            currentUser: {
                type: Object,
                required: true
            }
        }
    };
</script>

didn't tried it on logged in state yet, but I'll do any needed changes if needed.

Share:
31,042
Matipa Modisane
Author by

Matipa Modisane

Updated on July 05, 2022

Comments

  • Matipa Modisane
    Matipa Modisane almost 2 years

    I am using Vuejs as my frontend and I would simply like to get the current logged in user's id from Laravel and display it. How would I do this?

  • Haque
    Haque about 5 years
    Well I find this answer very suitable for me. Thanks but better do it like this @if(Auth::check()) <meta name="user-id" content="{{ Auth::user()->id }}"> @endif
  • Thijs
    Thijs about 5 years
    If the user isn't always logged in, you can also use optional like <meta name="user-id" content="{{ optional(Auth::user())->id }}">
  • Pablo
    Pablo almost 4 years
    How can I populate this.$userId to a textfield?