Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 635
Matipa Modisane Avatar asked Oct 08 '18 13:10

Matipa Modisane


1 Answers

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

like image 108
G-Wanje Avatar answered Oct 02 '22 11:10

G-Wanje