bockzior
bockzior

Reputation: 536

Why am I getting and "Undefined variable: var" error in Laravel?

I've been trying to pass some data to be avaliable in my views but after following several guides I always get a Undefined variable: var error.

I've added to app/Providers/AppServiceProvider.php in 2 different attemps:

Using share():

public function boot()
{
        // Make this custom global data avaliable to all views
        $var = "Foobar";
        view()->share('var', $var);
}

Using composer():

public function boot()
    {
            view()->composer('partials.navbar', function($view){
                $view->with('var', 'Foobar');
            });
    }

resources/views/partials/navbar.blade.php:

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li><a href="about">About</a></li>
    <li><a href="somewhere">{{$var}}</a></li>
</ul>

I'm completely new to Laravel so any help is greatly appreciated. Thanks!

Upvotes: 4

Views: 1861

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

Laravel pre-compiles certain files to improve performance. The AppServiceProvider is one of them...

To clear the pre-compiled classes, run php artisan clear-compiled and to pre-compile them again run php artisan optimize.

To change the classes that are pre-compiled and for more information on the topic in general, take a look at this answer

Upvotes: 1

Related Questions