Skip to content

Commit f75bd75

Browse files
committed
Omit configurable main locale prefix from URL
1 parent 9b68dd5 commit f75bd75

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

config/localized-routes.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,12 @@
77
*/
88
'supported-locales' => [],
99

10+
/**
11+
* If you have a main locale and don't want
12+
* to prefix it in the URL, specify it here.
13+
*
14+
* 'omit_url_prefix_for_locale' => 'en',
15+
*/
16+
'omit_url_prefix_for_locale' => null,
17+
1018
];

src/Macros/LocalizedRoutesMacro.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,25 @@ public static function register()
2121
$currentLocale = App::getLocale();
2222

2323
$locales = Config::get('localized-routes.supported-locales', []);
24+
$omitPrefix = Config::get('localized-routes.omit_url_prefix_for_locale');
2425

2526
foreach ($locales as $locale) {
2627
// Change the current locale so we can
2728
// use it in the callback, for example
2829
// to register translated route URI's.
2930
App::setLocale($locale);
3031

31-
// Wrap the localized routes in a group and prepend
32-
// the locale to the URI and the route name.
33-
Route::prefix($locale)->name("{$locale}.")->group($callback);
32+
// Create a new route and prepend
33+
// the locale to the route name.
34+
$route = Route::name("{$locale}.");
35+
36+
// Prefix the URL unless the locale
37+
// is configured to be omitted.
38+
if ($locale !== $omitPrefix) {
39+
$route->prefix($locale);
40+
}
41+
42+
$route->group($callback);
3443
}
3544

3645
// Restore the original locale.

tests/Unit/Macros/LocalizedRoutesMacroTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,31 @@ public function it_registers_a_root_route_for_each_locale()
6969
$this->assertContains('nl', $uris);
7070
}
7171

72+
/** @test */
73+
public function it_registers_a_url_without_prefix_for_a_configured_main_locale()
74+
{
75+
$this->setAvailableLocales(['en', 'nl']);
76+
77+
Config::set('localized-routes.omit_url_prefix_for_locale', 'en');
78+
79+
Route::localized(function () {
80+
Route::get('about', function () {})
81+
->name('about');
82+
});
83+
84+
$routes = $this->getRoutes();
85+
$names = $routes->pluck('action.as');
86+
$uris = $routes->pluck('uri');
87+
88+
$this->assertNotContains('about', $names);
89+
$this->assertContains('en.about', $names);
90+
$this->assertContains('nl.about', $names);
91+
92+
$this->assertNotContains('en/about', $uris);
93+
$this->assertContains('about', $uris);
94+
$this->assertContains('nl/about', $uris);
95+
}
96+
7297
/** @test */
7398
public function it_temporarily_changes_the_app_locale_when_registering_the_routes()
7499
{

0 commit comments

Comments
 (0)