Home > OS >  Laravel, how to substitute a variable in all urls of the project
Laravel, how to substitute a variable in all urls of the project

Time:10-06

I have a variable, i need to substitute it in all urls of the project. A little more detail: the session('locale') variable returns the site language 'fr' or another. I can't figure out how to substitute a variable into the default routes.

I got to the point of using links of the type <a href="{{session('locale')}}/page">Page</a> in the template(blade), but I don’t want to pile up the html-template, I want to solve the problem at the beginning routing so that all /page links by default go with the session('locale') route, those fr/page

Now the routing looks like this:

    [
        // Get Prefix Language ['en', 'fr']
        'prefix' => Localization::language(),
        'middleware' => 'language',
    ],
    function (){

        // Main Page
        Route::get('/', function () {
            return view('home.index');
        });

        // Language Page
        Route::get('/language', function () {
            return view('home.language');
        });
    }
);

CodePudding user response:

You can use URL Default values, you will need to create a middleware like setDefaultLanguage and in that middleware you will use

URL::defaults(['locale' => session('locale')]);

Now you are no longer required to pass the locale to each route you call. More information Here

In href you will have to use route() to work correctly.

  • Related