Wednesday, March 1, 2017

Access variable through view composer

I'm trying to get cities from database and pass them to two views through view composer. I've created a provider('ComposerSP') and have registered it at the providers at app.php:

'providers' => [
    App\Providers\ComposerSP::class,
]

ComposerSP's boot function contains this piece of code:

public function boot()
{
    View::composer(['register','user_admin'],'App\Http\ViewComposers\PagesComposer');
}

And the PagesComposer class looks like this:

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use App\Models\City;

class PagesComposer
{
    protected $cities;

    public function __construct()
    {
        $this->cities = City::pluck('city','id');
    }

    public function compose(View $view)
    {
        $view->with('cities',$this->cities);
    }
}

When i try to access variable $cities at the view register or user_admin, i get the error: 'Undefined variable: cities'. Thanks in advance.




via Arlind Hajdari

Advertisement