diff --git a/src/Config/language.php b/src/Config/language.php index 9473538..5ebd9fc 100644 --- a/src/Config/language.php +++ b/src/Config/language.php @@ -33,6 +33,17 @@ */ 'url' => false, + /* + |-------------------------------------------------------------------------- + | Set strategy + |-------------------------------------------------------------------------- + | + | This option will determine the strategy used to determine the back url. + | It can be 'session' (default) or 'referer' + | + */ + 'strategy' => 'session', + /* |-------------------------------------------------------------------------- | Carbon Language diff --git a/src/Controllers/Language.php b/src/Controllers/Language.php index 0b52ace..b8a96d5 100644 --- a/src/Controllers/Language.php +++ b/src/Controllers/Language.php @@ -57,6 +57,19 @@ public function back($locale, Request $request) { $this->setLocale($locale, $request); + $url = config('language.strategy') === 'referer' + ? $this->getUrlFromReferer($request) + : $this->getUrlFromSession($request); + + return redirect( + $url + ? $url + : (config('language.url') ? url('/' . $locale) : url('/')) + ); + } + + private function getUrlFromSession(Request $request) + { $session = $request->session(); if (config('language.url')) { @@ -72,10 +85,26 @@ public function back($locale, Request $request) $session->setPreviousUrl($url); } - return redirect( - $session->previousUrl() - ? $session->previousUrl() - : (config('language.url') ? url('/' . $locale) : url('/')) - ); + + return $session->previousUrl(); + } + + private function getUrlFromReferer(Request $request) + { + $url = $request->headers->get('referer'); + + if (config('language.url')) { + $url = substr(str_replace(env('APP_URL'), '', $url), 7); + + if (strlen($url) === 3) { + $url = substr($url, 3); + } else { + $url = substr($url, strrpos($url, '/') + 1); + } + + $url = rtrim(env('APP_URL'), '/') . '/' . $locale . '/' . ltrim($url, '/'); + } + + return $url; } }