如何使用Vuejs和Laravel获取当前已认证用户ID?

12

我正在使用Vuejs作为我的前端,我想从Laravel获取当前登录用户的id并将其显示出来。我该如何做到这一点?

6个回答

39

另一个选项是与 crsf 令牌的方式相同进行操作。

// 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)
}

8
我觉得这个答案非常适合我。谢谢,但最好像这样做:@if(Auth::check()) <meta name="user-id" content="{{ Auth::user()->id }}"> @endif - Haque
3
如果用户没有始终保持登录状态,您也可以使用可选项,例如 <meta name="user-id" content="{{ optional(Auth::user())->id }}"> - Thijs
我该如何将 this.$userId 填充到文本字段中? - Pablo

8

有许多方法可以获取授权用户ID 了解更多

Auth::user()->id;

Auth::id();

通过Vue.js

$http.get('api/user').then(response => {
   console.log(response.body);
})

2
如果你想将它传递给VueJS元素,你可以使用一个prop。例如: <custom :user-id={{Auth::id()}}></custom> - T. Altena
3
你假设他有Vue资源,但不确定。 - Oli Crt

3
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">

如果你将type属性从"hidden"改为"text",就能够测试并查看当前的id。


1
我需要将数据传递给我的Header组件,所以我想分享一下我正在使用的方法。
<fronend-header :current-user="{{ json_encode(['isLoggedIn'=>auth()->check() ? true : false, 'user'=>auth()->check() ? auth()->user() : null]) }}" />

在Vue.js方面
<script>
    export default {
        name: "frontend-header",

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

我还没有在登录状态下尝试过它,但如果需要的话,我会进行任何必要的更改。


0

你好,我尝试了上面的解决方案,但是因为还没有登录用户,所以出现了错误。Uncaught TypeError: Cannot read property 'getAttribute' of null 我添加了 @else 然后就可以了。 @if (Auth::check()) <meta name="user_id" content="{{ Auth::user()->id }}" />@else <meta name="user_id" content="0" /> @endif 希望能帮到其他人。


0
在 Laravel 9 中,我的情况是 app.js 中没有 Vue 对象,因为它是通过 createInertiaApp 初始化的。所以我找到了一种方法,只需修改 app.blade.php 和 Page.vue 文件即可实现。
简单来说:

app.blade.php:

window.user_id: {!! auth()->check()?auth()->user()->id:'null' !!}

Page.vue(顶部):

<script setup>
...
const user_id = window.user_id;
...

然后在我的Page.vue中,我可以在模板的任何地方使用{{ user_id }}。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接