LorienDarenya
LorienDarenya

Reputation: 509

Cannot share variable across all views in Laravel 5.1.4?

I'm very new to Laravel. As a blind programmer, I hope to utilize it to help me better improve my programming skills, speed, and accuracy. But I'm learning by hand as some videos are very visual. At this time, I'm trying to share a variable across all views and getting an undefined variable error.

I'm doing it by placing the following in the App\Http\Controllers\controller.php file:

public function __construct() {
$time = Carbon::now()->subMinute(5);
$users_online = User::where('last_active', '>', $time)
->where('last_active', '!=', '0000-00-00    00:00:00');
View::share('users_online', $users_online->count());
}

I'm calling it in various ways, none of which seem to work. Any help would be greatly appreciated.

For reference, I'm getting a variable not defined error.

Upvotes: 3

Views: 146

Answers (1)

izupet
izupet

Reputation: 1559

You should put all your global View variables in AppServiceProvider inside boot() method.

For example:

public function boot()
{
    $time = Carbon::now()->subMinute(5);
    $users_online = User::where('last_active', '>', $time)
        ->where('last_active', '!=', '0000-00-00    00:00:00');
    View::share('users_online', $users_online->count());
    ...
}

Upvotes: 1

Related Questions