0

I want to make a singleton binding of a domain model in register method of AppServiceProvider, but I have saved the id of the selected model in session and this information is not accessible in AppServiceProvider.

Has somebody any idea how I can solve my problem? This is my code.

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Domain::class, function ($app)
        {
            $request = request();

            if ($request->has('d'))
            {
                session(['domain' => $request->get('d')]);

                $domain = Domain::find($request->get('d'));
            }
            else
            {
                $domain = Domain::find(session('domain'));
            }

            return !is_null($domain) ? $domain : new Domain();
        });
    }

    public function boot()
    {
        //
    }
}

session('domain') is always null.

Thank you

  • This won't work as the `register` method is fired before the `StartSession` middleware is run. Where are you using the `Domain` class in your application? Are you planning on only using it in routes/controllers? – Rwd May 31 '19 at 11:04
  • I am using the Domain class in Middlewares and Controllers. I inject the Domain class in Middlewares and Controllers constructs. – joucogi May 31 '19 at 11:17

1 Answers1

0

You can use the session in your AppProvider, cause the MW didnt start till there. For more help or other ways read here: Link 1 Link 2

If you want to use the variable from your session inside the boot method you should use the view composer.

public function boot()
{
    view()->composer('*', function ($view) 
    {
        $view->with('myVar', \Session::get('varFromSession') );    
    });  
}
liqSTAR
  • 1,225
  • 1
  • 12
  • 22