adaba adaba - 3 months ago 11
PHP Question

How to generate url to routes with two languages in Laravel

Based on this thread I tried to implement extra english language for my website, default is french and doesn't use any prefix so something like
and switching to english would be
, I'd like to have the url for contact pages such as
for english and french version respectively.

My current routes.php

if (Request::segment(1) == 'en') {
Config::set('app.locale_prefix', Request::segment(1));
else {
Config::set('app.locale_prefix', '');

Route::group(array('prefix' => Config::get('app.locale_prefix')), function()
function () {
//return "main page - ".App::getLocale();
return view('index');
function () {
return view('contact');

My header file where the flag icon to switch language is

@if (Lang::locale() == 'fr')
<a href="{{ url('/en/' . Request::segment(1)) }}"><img src="{{asset('images/GB.png')}}"></a>
@elseif (strcasecmp(Request::segment(1), 'en') == 0 && Request::segment(2) != NULL)
<a href="{{ url( Request::segment(2)) }}"><img src="{{asset('images/FR.png')}}"></a>
<a href="{{ url( '/') }}"><img src="{{asset('images/FR.png')}}"></a>

and the way I generate urls

<a class="block-title" href="{{ (strcasecmp(Request::route()->getPrefix(), '/en') == 0) ? url('en/contact') : url('/contact') }}">CONTACT</a>

I'd like to know a cleaner way to generate these and how I can get for english main page url to be
instead of

Thanks a lot !


The best way to generate URL is:

First, give a name to yor routes:

//this route is called 'contact_route'
Route::get('/contact/', ['as' => 'contact_route', function () 
    return view('contact');

Routes are build dynamycally using the locale and the prefix, but once a route is defined and you've give it a name, you can create a URL for the route using the route helper with: route('contact_route')

Your example will become:

<a class="block-title" href="{{ route('contact_route') }}">CONTACT</a>

You can lear more of named routes in the docs

As for the trailing slash, the default Laravel .htaccess file, removes all the slashes at the end of the urls, with this rule:

RewriteRule ^(.*)/$ $1 [L,R=301]

That captures everything (.*) from the start ^ to the end before the slash /$ and substitute it with what is captured. So, if you want to add a trailing slash, probably you should edit the .htaccess file