Retrieve User Name in Vue.js

Published 1 week ago by frutos93

I have an vue component in which I would like to send the logged user name and it's structured this way:

export default {
        data(){
            return{
                messageText: ''
            }
        },
        methods:{
            sendMessage(){
                this.$emit('messagesent', {
                    message:this.messageText,
                    user: {
                    name: Auth()::user()->name
                            }
                });
                this.messageText = '';
            }
        }
    }

Auth user doesn't work, it throws an error.

Auth()::user()->name

How can I retrieve the logged user name in a vue method?

Best Answer (As Selected By frutos93)
ncrousset

You use props and pass it on when calling the component

export default {
        data(){
            return{
                messageText: ''
            }
        },
     props: {
            userName: String ,
    },
        methods:{
            sendMessage(){
                this.$emit('messagesent', {
                    message:this.messageText,
                    user: {
                    name: this.userName
                            }
                });
                this.messageText = '';
            }
        }
    }

and

<my-component :user-name={{ Auth::user()->name }}></my-componet>
shawn.rinehart

You can't call PHP methods from .js or .vue files. For a quick and easy solution, check out this Laracasts package or consider creating some API endpoints to retrieve the data you need.

ncrousset

You use props and pass it on when calling the component

export default {
        data(){
            return{
                messageText: ''
            }
        },
     props: {
            userName: String ,
    },
        methods:{
            sendMessage(){
                this.$emit('messagesent', {
                    message:this.messageText,
                    user: {
                    name: this.userName
                            }
                });
                this.messageText = '';
            }
        }
    }

and

<my-component :user-name={{ Auth::user()->name }}></my-componet>

Sign In or create a forum account to participate in this discussion.