mercredi 27 juillet 2016

How to properly filter this Route code in Laravel 5?

I have the follow Route:

Route::get('/{lang?}', array('as'=>'URL',function ($lang=NULL) {

    //Retrieve the environment from URL string -> fist 2 characters.
    $env = substr(URL::route('URL'), 7, 2);
    //Store the $env inside the $_SESSION['env']
    Session::set('env', $env);

    if(is_null($lang)){
      //do some stuffs ....
    }

    return view('index');
}));

The goal of this code is to retrieve the URL and grab the first 2 characters that will be the evironment($env).

The code expect to receive the language parameter as optional. If the user types URL=us.mysite.com/es the code will delivery the index page in spanish for the US enviroment.

If nothing is sent as language, like URL=us.mysite.com, there is an array inside the code that will tell the default language to US environment.

So far so good, it works nice.

But now I have an issue. I would like to send the user to the home page trough the follow route code:

Route::get('/home', function () {
    return view('home');
});

The issue is that Route::get('/home' is going to Route::get('/{lang?}' and there I get an error because the code do not expect to processing this word.

After reading the documentation for Routes, I have created filters inside the first Route code that should grab only the expected languages strings like en, sp, fr.

So this is the code now:

Route::get('/{lang?}', array('as'=>'URL',function ($lang=NULL) {

    //Retrieve the environment from URL string -> fist 2 characters.
    $env = substr(URL::route('URL'), 7, 2);
    //Store the $env inside the $_SESSION['env']
    Session::set('env', $env);

    if(is_null($lang)){
      //do some stuffs ....
    }

    return view('index');
}))->where('lang', '[en|es|fr]');

This approach is not working. Now I have this error NotFoundHttpException in RouteCollection.php line 161:, when I try URL=us.mysite.com/es, and when I try URL=us.mysite.com/home I get the error No such file or directory.

The final goal is if the user will type URL=us.mysite.com without lang parameter or URL=us.mysite.com/en or es or fr with expected parameter the request should be processed inside the Route::get('/{lang?}'. If the user will type URL=us.mysite.com/home the request should skip the Route::get('/{lang?}' route and should be processed inside Route::get('/home'.

So, I dont know what I am doing wrong. Any idea?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire