code-8
code-8

Reputation: 58702

Share a variable through out Laravel application

I have a variable.

$key_test = 123456789;

I want to be able to access this 1 variable anywhere in my app even in config files, models, controllers, and views.

I've tried adding it in my boot():

<?php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\VSE, App\CURL;
use View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        $key_test = 123456789;

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

I've tried to access it in one of my config file. I kept getting null.

<?php

dd($key_test); <---- null

return [ ... ]; 

How do I access that variable in my config file?

Did I do it right in my boot()?

Upvotes: 0

Views: 657

Answers (3)

Ian
Ian

Reputation: 3676

You can use a helper method for config.

config(['key_test'=>123456789])

Then access it through the same way,

config('key_test')

Upvotes: 4

LF-DevJourney
LF-DevJourney

Reputation: 28524

you have some choice here, for global variable, session, file, db, or in the memory with redis or memcache.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Put this variable into the .env file:

VAR=123456789;

Then you'll be able to access it with env('VAR'); from config files, models, controllers and other classes.

Upvotes: 3

Related Questions