lundi 23 novembre 2015

Laravel 5: Get locale from URI

I am kinda stuck with how to make the routes for a multi lingual site made using Laraval 5. What I want is an url like site.com/home or site.com/en/hometo fetch the default language (en version in this case) of home content and site.com/nl/home to fetch the Dutch content of home. But also a url like http://ift.tt/1X9h3Qc and http://ift.tt/1X9h2Me should work like this.

So when there is no part 1 in the uri it defaults to the default language (in this case en) and if there is, it fetches the content for this language.

My routes now look like this:

Route::pattern('slug', '[a-zA-Z0-9\-_\/]+');
    if(isset($_SERVER['REQUEST_URI'])) {
        $slug = $_SERVER['REQUEST_URI'];
        // chop slug in array
        $slug = explode('/', $slug);

        if(in_array($slug[1], Language::all()->lists('iso'))) {
            die('language found, some other logic should come here');
        }

        if(!$slug[1]) {
            Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page'])->where('slug', 'home');
        } else {
            if($slug[1] != 'dashboard' && $slug[1] != 'migrate') {
                // if only one slug, go to PagesController@page
                if (in_array($slug[1], ElementValue::where('element_field_id', 2)->lists('value_char')) && !isset($slug[2])) {
                    Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page'])->where('slug', '[a-zA-Z0-9\-_\/]+');
                    // if there is a second slug, go to PagesController@element
                } elseif (in_array($slug[2], ElementValue::where('element_field_id', 2)->lists('value_char'))) {
                    Route::any('/{slug}', ['as' => 'pages.element', 'uses' => 'PagesController@element'])->where('slug', '[a-zA-Z0-9\-_\/]+');
                } else {
                    Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page'])->where('slug', 'home');
                }
            }
        }
    }

I tried to change the second slug into the first if there is a locale, but this doesn't work:

if(in_array($slug[1], Language::all()->lists('iso'))) {
    $slug[1] = $slug[2];
    $slug[2] = $slug[3];
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire