How to get current authenticated user id using Vuejs and Laravel?
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
by many way to get auth user id read more
Auth::user()->id;
Auth::id();
by vue js
$http.get('api/user').then(response => {
console.log(response.body);
})
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)
}