Artur Grigio
Artur Grigio

Reputation: 5553

Where are Laravel Vue env variables?

I'm using Vue.js 2.0 with Laravel. Laravel has a .env file that allows you to do:

$foo = env('bar', 'somekey');

But if I want my variable bar in Vue.js components, have to do something like this:

IN BLADE:

var bar = '{{ env('bar') }}';

IN VUE:

data {
    ...
    foo: bar
}

This doesn't seem to be the most elegant way of achieving the desired result.

I see that when I run npm run production script, there is a part that does:

cross-env NODE_ENV=development ...

So I have 2 questions:

  1. Where is the env file that development is referring to, so I can add my variables to it?

  2. How do I access those variables in my Vue components?

Upvotes: 1

Views: 1560

Answers (1)

Aida
Aida

Reputation: 171

Not sure if it's exactly what you are looking for, but here is an article about "Sharing Data in a Laravel/Vue application". https://zaengle.com/blog/layers-of-a-laravel-vue-application

Read the section "Data Transfer Strategies".

//Blade Template
<script>
    window.Laravel = <?php echo json_encode([
         'csrf_token => csrf_token(),
         'user'      => $user
    ]); ?>
</script>

<my-custom-vue-component></my-custom-vue-component>


//Vue Component
data(){
    return {
        user: window.Laravel.user
    }
}

Upvotes: 1

Related Questions