How to Use Environment Variables in Laravel Vue JS App?

Laravel 9 , Vue.Js

Nicesnippets

25-07-2022


How to Use Environment Variables in Laravel Vue JS App?

Hello Friends,

In this quick example, let's see How to Use environment Variables form Laravel in Vue js. I would like to share with you laravel vue js get .env variable value. you will learn Add Laravel .env variable to Vue component. I explained simply about Use laravel .env variable in Vue.

Here, i will add "VITE_APP_NAME" variable with "Vite Title" value in .env file file. Then i will use "VITE_APP_NAME" variable in vue js file. i will access environment variable using "import.meta". let's follow below example.

Let's see bellow example How to access Laravel .env variables in Vue JS.

Step 1: Set Variable in .env File


We will add VITE_APP_NAME variable with value in .env file. so let's add it on .env file.

VITE_APP_NAME="Vite Title"

Step 2: Get .env Variable in Vue JS

Solution:

const appName = import.meta.env.VITE_APP_NAME;

Example:

/resources/js/app.js

import './bootstrap';

import '../css/app.css';

import { createApp, h } from 'vue';

import { createInertiaApp } from '@inertiajs/inertia-vue3';

import { InertiaProgress } from '@inertiajs/progress';

import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';

import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';

const appName = import.meta.env.VITE_APP_NAME;

createInertiaApp({

title: (title) => `${title} - ${appName}`,

resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),

setup({ el, app, props, plugin }) {

return createApp({ render: () => h(app, props) })

.use(plugin)

.use(ZiggyVue, Ziggy)

.mount(el);

},

});

InertiaProgress.init({ color: '#4B5563' });

now it works...

I hope it can help you...