Lovelock
Lovelock

Reputation: 8085

Laravel View::share

Trying to work out a way to use global variables without actually creating a global variable.

I am working on a framework that I will use for all future projects and wish to have a database table containing the websites changing features (site name, colours, logo link etc)

If I wasn't using Laravel I would just include a functions file into my header include which set up an array of all these values so I could just call it.

<?= $constants['business_name] ?>

In Laravel, I could make a function to take a name and then return the value but seems excessive waste of db calls.

I found:

View::share

But I am getting variable undefined errors.

Tried this:

public function __construct()
{
    $constants = DB::table('constants')->get();
    return $constants;
    View::share('constants', $constants);
}

In my BaseController but the error is shown, any idea?

Upvotes: 0

Views: 484

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152950

You return from the constructor before even calling View::share()

public function __construct()
{
    $constants = DB::table('constants')->get();
    return $constants;  // <<<<<<
    View::share('constants', $constants);
}

Actually a constructor should never return something, so removing that line will do:

public function __construct()
{
    $constants = DB::table('constants')->get();
    View::share('constants', $constants);
}

You might also want to look into view composers to make data globally available without the need for a constructor:

View composers - Laravel docs

Upvotes: 2

Related Questions