Mr.Singh
Mr.Singh

Reputation: 1781

Laravel: access view composer's data in other file(s)

I have a view composer file called statistics.blade.php which is accessed on every page in the application(also included on the dashboard). On the dashboard page the same set of data is displayed in the form tiles.

class StatisticsComposer
{
    public function compose(View $view)
    {
        # models
        $ModelA  = new ModelA();
        $ModelB  = new ModelB();
        $ModelC  = new ModelC();

        ...

        # binding data
        $view->with('arrayStatistics', [
            'ModelA'  => $ModelA->_someMethod(),
            'ModelB'  => $ModelB->_someMethod(),
            'ModelC'  => $ModelC->_someMethod(),

            ...
        ]);
    }
}

I need to access this arrayStatistics array on the dashboard index file. Is it possible..?

Upvotes: 1

Views: 484

Answers (1)

Ersoy
Ersoy

Reputation: 9596

After you created your StatisticsComposer then you need to boot it in service provider.

Create a service provider called ComposerServiceProvider such as ;

class ComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::composer(['statistics'], StatisticsComposer::class); // assuming it is in `resources` folder

        // other view composer bindings...
    }
}

and at it to app.php's providers array such as;

'providers' => [
     // ... other providers
     App\Providers\ComposerServiceProvider::class,
],

Then $arrayStatistics will be accessible on your statistics.blade.

Edit: I think it is better to not use arrayStatistics but ModelA, ModelB directly for direct usage/access.

Upvotes: 1

Related Questions