如何使用 Vuejs 和 Laravel 获取当前经过身份验证的用户 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52703364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:06:19  来源:igfitidea点击:

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

javascriptphplaravelauthenticationvue.js

提问by Matipa Modisane

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?

我使用 Vuejs 作为我的前端,我只想从 Laravel 获取当前登录的用户 ID 并显示它。我该怎么做?

采纳答案by Matipa Modisane

by many way to get auth user id read more

通过多种方式获取身份验证用户 ID阅读更多

Auth::user()->id;

Auth::id();

by vue js

通过 Vue.js

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

回答by Thijs Bouwes

Other option is to do it the same way as the crsftoken.

另一种选择是按照与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)
}

回答by AbdessamadEL

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

我需要将数据传递给我的 Header 组件,所以我想我可以分享我的做法

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

On the vuejs side

在 vuejs 方面

<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.

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