Riaan
Riaan

Reputation: 195

Get route paramater in AppServiceProvider

I have a company parameter set in every route in my application. I am trying to send the variable for that company to each view for easy access.

In my AppServiceProvider.php I tried two things:

$company = App::make('request')->route()->getParameter('company');
view()->share('company', $company);

and also:

$company = Route::getCurrentRoute()->getParameter('company');
view()->share('company', $company);

But with both of them I get the error:

Call to a member function getParameter() on a non-object

How would I go about getting the parameter variable?

Edit:

I am doing it in the boot() function

Answer:

All I did was do the following in my register() function in AppServiceProvider:

 view()->composer('*', function ($view) {
            // all views will have access to current route
            $view->with('company', \Route::getCurrentRoute()->getParameter('company'));
        });

Upvotes: 4

Views: 4069

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

Current route is not yet known in AppServiceProvider as the application is still being bootstrapped here. If you want to access route parameters, you could use a view composer - see more details here https://laravel.com/docs/5.1/views#view-composers.

A quick example:

class AppServiceProvider extends ServiceProvider {
  public function register()
  {
    view()->composer('*', function ($view) {
        // all views will have access to current rout
        $view->with('current_route', \Route::getCurrentRoute());
    });
  }
}

Upvotes: 3

Related Questions