What's the best logic for switching language in Laravel?

后端 未结 8 1655
遥遥无期
遥遥无期 2020-12-23 02:29

I\'m using Laravel localization to provide two different languages. I\'ve got all the path stuff set up, and mydomain.com/en/bla delivers English and stores the \'en\' sessi

8条回答
  •  悲&欢浪女
    2020-12-23 02:57

    What I'm doing consists of two steps: I'm creating a languages table which consists of these fields:

    id | name | slug

    which hold the data im gonna need for the languages for example

    1 | greek | gr

    2 | english | en

    3 | deutch | de

    The Language model I use in the code below refers to that table.

    So, in my routes.php I have something like:

    //get the first segment of the url
    $slug = Request::segment(1);   
    $requested_slug = "";
    
    //I retrieve the recordset from the languages table that has as a slug the first url segment of request
    $lang = Language::where('slug', '=', $slug)->first();
    
    //if it's null, the language I will retrieve a new recordset with my default language
    $lang ? $requested_slug = $slug :  $lang = Language::where('slug', '=', **mydefaultlanguage**')->first();
    
    //I'm preparing the $routePrefix variable, which will help me with my forms
    $requested_slug == ""? $routePrefix = "" : $routePrefix = $requested_slug.".";
    
    //and I'm putting the data in the in the session
    Session::put('lang_id', $lang->id);
    Session::put('slug', $requested_slug);
    Session::put('routePrefix', $routePrefix );
    Session::put('lang', $lang->name);
    

    And then I can write me routes using the requested slug as a prefix...

    Route::group(array('prefix' =>  $requested_slug), function()
    {
        Route::get('/', function () {
            return "the language here is gonna be: ".Session::get('lang');
        });
    
        Route::resource('posts', 'PostsController');
        Route::resource('albums', 'AlbumsController');
    });
    

    This works but this code will ask the database for the languages everytime the route changes in my app. I don't know how I could, and if I should, figure out a mechanism that detects if the route changes to another language.

    Hope that helped.

提交回复
热议问题