DEV Community

Cover image for Use laravel .env variable in Vue
Graham Morby
Graham Morby

Posted on

Use laravel .env variable in Vue

This used to drive me nuts, many times I wanted a .env in Vue that was easy to use and maintain. So when I had a Laravel back end I found the best way was to use the .env that comes with Laravel and pull variables from there.

So how do we do it?

Let's say we have an API key and of course we do not want people to be able to see it on the Javascript end. We start by defining the variable in the .env. We define mixable variables using 'MIX'.

MIX_API_KEY=this_will_be_our_key
Enter fullscreen mode Exit fullscreen mode

So as long as we run

php artisan config:clear

we can now use the variable in our component.

To use it we simply call

process.env.MIX_API_KEY
Enter fullscreen mode Exit fullscreen mode

In the real world, it will look like so

data() {
   return() { 
     api_key: process.env.MIX_API_KEY
  }
}
Enter fullscreen mode Exit fullscreen mode

and perfection! We can now use the laravel .env file to host and use any variables we don't want to store in javascript.

Top comments (3)

Collapse
 
irfanullahshakir profile image
Irfan Ullah Shakir

I have an issue I want to access variables inside .env through process.env.VARIABLE_NAME, but give me some error.I am working on laravel Pusher with VueJs.

bootstrap.js

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

Vue.prototype.$echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});

My Vue File

    mounted() {
        Vue.prototype.$echo.private('expense')
        .listen('ExpenseNotification', (e) => {
            console.log('irfan ullah shakir');
        });
    }

Error:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'private' of undefined"

Code works fine to broadcast event to pusher, but have problem in receiving through 'Echo'

Collapse
 
grahammorby profile image
Graham Morby

Have you re complied ?

npm run dev
yarn run dev 

etc

Collapse
 
irfanullahshakir profile image
Irfan Ullah Shakir

Thank you I already solved it, here is my solution:
dev.to/irfanullahshakir/comment/15en1