Daniel Katz
Daniel Katz

Reputation: 2408

Laravel pass a certain parameter to all routes in all views

I needed to pass a subdomain name to all views so that when they generate routes with route('namedRoute') users will end up in the same subdomain.

I ended up creating a ViewServiceProvider which registers a view composer where I get the subdomain from the request like so:

    use Illuminate\Support\Facades\View as FView;
    use Illuminate\View\View;

    class ViewServiceProvider extends ServiceProvider {
         FView::composer('*', function(View $view){
             $view->with('subdomain', request()->route()->subdomain);
         });
    }

This way the subdomain variable will be passed to every singe view every time thanks to the '*' as documented in Laravel docs.

Then when I need to generate any route in any view, I will always have to pass the subdomain like so and the route will be generated correctly.

    {{ route('signInPage', ['subdomain' => $subdomain]) }}

So is there something in laravel (like a post view processing) that I can hook into to populate the subdomain automatically so I don't have to now modify every route generation in every view?

Upvotes: 1

Views: 920

Answers (1)

lagbox
lagbox

Reputation: 50481

The URL generator can take defaults so you don't have to pass a paremeter for the route when generating the URL:

URL::defaults(['subdomain' => ....]);

You can create a route middleware that gets the subdomain parameter from the request and sets this default.

Laravel 8.x Docs - URLs - Default Values

Upvotes: 2

Related Questions