Tyler Shannon
Tyler Shannon

Reputation: 309

Laravel View Composer "Cannot use object of type Closure as array"

I am using an array for my view composer and it throws this error when I try to view the page Cannot use object of type Closure as array.

I tried using eloquent instead for the variable but that didn't end up working because that is not how it is supposed to be structured the way I am using them. I've also tried creating a function within the $view->with()variable.

public function compose(View $view)
    {
        $view->with('configurable', function() {
            $configurables = Cache::rememberForever('configurables', function() {
                return Configurables::all();
            });
            $configurable = [];
            foreach($configurables as $key) {
                $configurable[$key->slug] = [
                    'value' => $key->value
                ];
            }

            return $configurable;
        });
    }

Upvotes: 0

Views: 714

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

The error means that with() method expects a value, not a function (closure). You can refactor your code like following:

public function compose(View $view)
{

        $configurables = Cache::rememberForever('configurables', function() {
            return Configurables::all();
        });

        $configurable = [];

        foreach($configurables as $key) {
            $configurable[$key->slug] = [
                'value' => $key->value
            ];
        }

       $view->with('configurable', $configurable);
}

Hope this helps.

Upvotes: 1

Related Questions