lundi 24 juin 2019

Laravel Multi-language Route Prefix

I managed to get some routes working with and without a prefix. Having routes that do not have the prefix work properly is important as it's too much work to go back and change all get/post links to the correct localized ones.

For example with the code below the url localhost/blog redirects to localhost/en/blog (or any other language stored in session).

However, I noticed that URLs with parameters dont work, so /blog/read/article-name will result in a 404 instead of redirecting to /en/blog/read/article-name.

Routes:

Route::group([
  'prefix' => '{locale}',
  'middleware' => 'locale'],
  function() {
  Route::get('blog', 'BlogController@index');
  Route::get('blog/read/{article_permalink}', 'BlogController@view');
  });

Middleware responsible for the redirects which doesnt seem to fire at all for some routes, as if the route group isn't matching the url.

    public function handle($request, Closure $next)
    {
      if ($request->method() === 'GET') {
          $segment = $request->segment(1);

          if (!in_array($segment, config('app.locales'))) {
              $segments = $request->segments();
              $fallback = session('locale') ?: config('app.fallback_locale');
              $segments = array_prepend($segments, $fallback);

              return redirect()->to(implode('/', $segments));
          }

          session(['locale' => $segment]);
          app()->setLocale($segment);
      }

      return $next($request);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire