88use Illuminate \Support \Facades \Config ;
99use Illuminate \Support \Facades \Request ;
1010use Illuminate \Support \Facades \Route ;
11+ use Symfony \Component \Routing \Exception \RouteNotFoundException ;
1112
1213class LocalizedUrlGenerator
1314{
@@ -49,6 +50,10 @@ public function generateFromRequest($locale = null, $parameters = null, $absolut
4950 $ locale = $ locale ?: $ this ->detectLocale ($ urlBuilder );
5051 $ parameters = $ this ->prepareParameters ($ locale , $ parameters ?: $ this ->getRouteParameters ());
5152
53+ if ($ url = $ this ->generateFromNamedRoute ($ locale , $ parameters , $ absolute )) {
54+ return $ url . $ urlBuilder ->getQueryString ();
55+ }
56+
5257 if ( ! $ this ->is404 ()) {
5358 $ urlBuilder ->setPath ($ this ->replaceParameters ($ this ->route ->uri (), $ parameters ));
5459 }
@@ -64,6 +69,67 @@ public function generateFromRequest($locale = null, $parameters = null, $absolut
6469 return $ urlBuilder ->build ($ absolute );
6570 }
6671
72+ /**
73+ * Generate a URL for a named route.
74+ *
75+ * @param string $locale
76+ * @param array $parameters
77+ * @param bool $absolute
78+ *
79+ * @return string
80+ */
81+ protected function generateFromNamedRoute ($ locale , $ parameters , $ absolute )
82+ {
83+ if ( ! $ this ->routeExists ()) {
84+ return '' ;
85+ }
86+
87+ $ name = $ this ->route ->getName ();
88+
89+ // Localized routes without a name will still have the locale prefix as a name.
90+ // Strip the prefix from the name to make sure the route has a base name set.
91+ if ($ this ->stripLocaleFromRouteName ($ name ) === '' ) {
92+ return '' ;
93+ }
94+
95+ try {
96+ return route ($ name , $ parameters , $ absolute , $ locale );
97+ } catch (RouteNotFoundException $ e ) {
98+ return '' ;
99+ }
100+ }
101+
102+ /**
103+ * Strip the locale from the beginning of a route name.
104+ *
105+ * @param string $name
106+ *
107+ * @return string
108+ */
109+ protected function stripLocaleFromRouteName ($ name )
110+ {
111+ $ parts = explode ('. ' , $ name );
112+
113+ // If there is no dot in the route name,
114+ // there is no locale in the route name.
115+ if (count ($ parts ) === 1 ) {
116+ return $ name ;
117+ }
118+
119+ $ locales = $ this ->getLocaleKeys ();
120+
121+ // If the first part of the route name is a valid
122+ // locale, then remove it from the array.
123+ if (in_array ($ parts [0 ], $ locales )) {
124+ array_shift ($ parts );
125+ }
126+
127+ // Rebuild the normalized route name.
128+ $ name = join ('. ' , $ parts );
129+
130+ return $ name ;
131+ }
132+
67133 /**
68134 * Check if the current route is localized.
69135 *
0 commit comments