简体   繁体   中英

Accessing Laravel's .env variables inside Inertia.js Vue files

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?

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!

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 }}

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>

if you want to share multiple variables with view use the following:

Inertia::share('app', [
        'name' => config('app.name'),
        'url' => config('app.url'),
    ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM