Search code examples
laravelglobal-variableslaravel-blade

Laravel shared data from external resource fetched by HTTP in view composer


I would like to share global data for all blades which is fetched from an external API. For this reason I created a ViewServiceProvider which boots as it follows
View::composer('*', CommonsComposer::class);

than in composer I would like to fetch the data as it follows

public function __construct()
{
    try {
        $response = Http::get(env('WP_API_URL') . 'bdb/v1/options');
        $this->wpData = $response->json();
    } catch (HttpException $exception) {
        dump($exception);
    }
}

but here is not best place to do this because when a blade template is rendered then the call would be fired as well.

How to limit the HTTP call to one request?


Solution

  • We think you can register composer class with singleton pattern. Something like this:

    In ViewServiceProvider :

    public function register()
    {
        $this->app->singleton(\path_to_composer\CommonsComposer::class);
    }