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?
6 Answers
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)
}
3 Comments
@if(Auth::check()) <meta name="user-id" content="{{ Auth::user()->id }}"> @endif<meta name="user-id" content="{{ optional(Auth::user())->id }}">this.$userId to a textfield?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);
})
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
Comments
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.
Comments
In my case in Laravel 9 I don't have Vue object inside app.js as it's initiated via createInertiaApp. So I have found a way to do this by modifying only app.blade.php and my Page.vue file.
Simply:
app.blade.php:
window.user_id: {!! auth()->check()?auth()->user()->id:'null' !!}
Page.vue (the very top):
<script setup>
...
const user_id = window.user_id;
...
And then inside my Page.vue I can use {{ user_id }} anywhere inside the template.
Comments
Hi I tried the above solutions but I'm getting an error because there's no logged in user yet. Uncaught TypeError: Cannot read property 'getAttribute' of null
I added @else then is worked.
@if (Auth::check()) <meta name="user_id" content="{{ Auth::user()->id }}" />@else <meta name="user_id" content="0" /> @endif hope will help someone