cshelswell
cshelswell

Reputation: 83

Creating a Global Variable in the AppServiceProvider Laravel 5.3

Hi I have posted this on Laracasts but so far no answers so thought I'd try here :)

I'm trying to get a couple of global variables to views using the AppServiceProvider. I've not had a problem if I use one of Laravel's facades to get user details for example but with dependency injection I've not been able to work it out.

This is the code I currently have:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Repositories\ShopCategory\ShopCategoryInterface;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(ShopCategoryInterface $shop_category)
    {
        $parent_categories = $shop_category->getParentCategories();

        view()->composer('*', function($view){
            $view->with('parent_categories', $shop_category->getParentCategories());
    });
}

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

    }
}

I had assumed this would work but I get the error:

Undefined variable: shop_category

So i'm just wondering how I pass the $shop_category class to the view composer.

Thanks for any help

Upvotes: 0

Views: 2932

Answers (2)

You need to use() function into the closure for pass var inside function

Try this:

    view()->composer('*', function($view) use($shop_category) {
        $view->with('parent_categories', $shop_category->getParentCategories());
    });

Upvotes: 1

Nazmul Hasan
Nazmul Hasan

Reputation: 1987

boot function should be

 public function boot()
    {
        view()->composer('*', function($view){
        $shop_category = new ShopCategoryInterface()
        $parent_categories = $shop_category->getParentCategories();
        $view->with('parent_categories', $shop_category->getParentCategories());
    });

Upvotes: 0

Related Questions