0
votes

I'm setting up some Vue Components in my Laravel 5.8 application, that require user information available through Auth::user(), most importantly, the api_token that I must use in my axios requests. I want to pass the Auth::user() object from Laravel to Vue in a secure and private method.

I initially passed the object as props, but I don't want private information on the object to be easily exposed using browser extensions such as Vue DevTools. Now, I've been searching for a way to define global variables inside the Blade Template and access them in Vue:

Pass data from blade to vue component

https://forum.vuejs.org/t/accessing-global-variables-from-single-file-vue-component/638

https://zaengle.com/blog/layers-of-a-laravel-vue-application

Based on those links above, it seems like what I need to do is set the variables to the window object, but I'm unsure on what I'm doing something wrong to achieve this. When I define the variable in the Blade Template, I can see the variable is assigning properly by doing console.log() but the problem comes when I try to use it in Vue.

app.blade.php

@if(Auth::user())
    <script>
        window.User = {!! json_encode(Auth::user()) !!}
        console.log(window.User)
    </script>
@endif

component.vue

<script>
export default {
    data: function() {
        return {
            user: window.User
        }
    }
}
</script>

I've tried setting the data as window.User, this.User, and simply just User but it always comes up as undefined. What am I missing? Or is there any other/better way to do this?

1
I tried console.log(window.User) and the console print the user data normally.Phil
If you pass something to JS, it'll be accessible from the browser. Though, not "secure" or "private"Tarasovych
Anyway, Vue DevTools are available when you run npm run dev, on production you have to go with npm run build or something similar, maybe npm run prodTarasovych
@Phil Yes, as I said, the console.log() does display the data, but when I try to assign it to a variable in Vue, like user: window.User it says it's undefined.AndrykVP
@Tarasovych So my variables and components won't show up once I build in production? My goal is simply to not have the data user readable by third party tools, so if the props do not appear in DevTools, I might stick to that solutionAndrykVP

1 Answers

0
votes

Try the following Vue Component:

<template></template>

<script>
    export default {
        data: function() {
            return {
                user: window.User
            }
        },
        created(){
            console.log(this.user)

        },
    }
</script>

I could see the user data from the console.log in Vue component.