Reputation: 1340
I am starting with the Inertia Laravel example https://github.com/drehimself/inertia-example
which is nothing but Laravel with Vue in one monolithic codebase, using Inertia.js: https://github.com/inertiajs/inertia-laravel https://github.com/inertiajs/inertia-vue
I am trying to access Laravel's .env variables inside my .vue component files
.env file:
APP_NAME=ABC
In app\Providers\AppServiceProvider.php:
public function register()
{
Inertia::share('appName', env('APP_NAME'));
}
In resources\js\Home.vue component:
<template>
<div>
<span class="tw-text-left">{{ appName }}</span>
</div>
</template>
<script>
export default {
props: [
"appName",
]
}
</script>
In my vue console, appName shows up blank. It should show "ABC" but doesn't. What's going on here, and how I can access all my env variables, ideally without passing everything through the controller, which doesn't seem very efficient?
Upvotes: 8
Views: 10935
Reputation: 576
if you are using inertia with vite, you can access like below
const cek = import.meta.env.VITE_GEO_API_BASE_URL
console.log(cek)
you can read more about vite env https://dev.to/arielmejiadev/load-laravel-env-variables-into-client-code-with-vite-9ld
Upvotes: 1
Reputation: 524
if you want to share multiple variables with view use the following:
Inertia::share('app', [
'name' => config('app.name'),
'url' => config('app.url'),
]);
Upvotes: 1
Reputation: 680
I know this is kind of old, but I ran into this same issue and the methods above and around the net did not work for me. Something might have changed with Inertia? Anyway, I did get it working though.
Just like above add the following to the register method within your AppServiceProvider:
Inertia::share('appName', config('app.name'));
// I'm using config, but your could use env
Then in your Vue component access the $inertia
variable like so:
{{ $inertia.page.props.appName }}
Upvotes: 6
Reputation: 1340
I finally got it working. Here's how, for those interested: In AppServiceProvider:
Inertia::share(function () {
return [
'app' => [
'name' => config('app.name'),
],
];
});
In your vue file:
<template>
<div>
App name: {{ $page.app.name }}
</div>
</template>
The 2nd part is what I was missing..I was trying to accept the app.name prop, and was missing $page. Hope this helps somebody!
Upvotes: 5
Reputation: 3128
From the documentation on the author's website, you need to instruct vue to inject the page
into your component, and then you can accessed the shared variables.
For example:
<template>
<div>
<span class="tw-text-left">{{ page.props.appName }}</span>
</div>
</template>
<script>
export default {
inject: ['page'],
// ...
}
</script>
Upvotes: 1