Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 965
Adel Wafa Avatar asked Sep 10 '25 11:09

Adel Wafa


2 Answers

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
}
like image 144
Raymond Cheng Avatar answered Sep 13 '25 12:09

Raymond Cheng


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.

like image 27
Niklesh Raut Avatar answered Sep 13 '25 13:09

Niklesh Raut