Adel Wafa
Adel Wafa

Reputation: 41

Laravel url previous return same page after page reload

I tried to access the previous URL on Laravel 5.3 Homestead by several methods but all times i got the right previous page at first request then i got the same page after i refresh the page.

I am using Middleware to check the language before accessing the page

URL::previous();
// or
back()->getTargetUrl();

Language middleware

    public function handle($request, Closure $next, $guard = null) {
    $locale = $request->locale;
    $segments = $request->segments();
    $lang_sess = $request->session()->get('language');

    if (!array_key_exists($locale, Config::get('app.locales'))) :
        if (count($segments) > 1):
            $segments[0] = ($lang_sess == "") ? Config::get('app.fallback_locale') : $lang_sess;
            $re_to = implode('/', $segments);
        else:
            $locale = $request->session()->get('language', 'en');
            $re_to = "/$locale/" . implode('/', $segments);
        endif;
        return Redirect::to($re_to);
    endif;
    $request->session()->put('language', $locale);
    App::setLocale($locale);
    return $next($request);
}

[SOLVED]

as i still developing my web app, i didn't go the page through a 'href' link, i was entering it through copy and paste the URL into browser, and this causes the URL::previous to be changed after reload the page..

Case closed, thanks for all who replied and gave attention.

Upvotes: 4

Views: 7546

Answers (2)

Raymond Cheng
Raymond Cheng

Reputation: 2505

the 'previous URL' is stored in a session.Every time your URL changes, the session()->get('_previous')['url'] will change to previous url.

Doing the logic this way:

if (url()->current() == url()->previous()) {
    url()->setPreviousUrl('xxx') // or other logic here
}

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

If you go to page A from B . Your previous page will be B . But if you refresh page then you are going from A to page A.

I suggest to use cookie in this case by checking previous page , if different change cookie otherwise keep it as it is.

  $last_page = URL::previous();
  if(Cookie::get("previous_page") == $last_page){
       Cookie::make('previous_page',$last_page, 60);
  }

Now you can use this cookie value Cookie::get ("previous_page") in your middleware

Not tested but this would guide you.

Upvotes: 1

Related Questions