8

In Laravel, there is a function return back();, which returns the user to the previous page. Is it possible to return back(); more than once within one function to return the user back twice or several times? I tried

public function ....()
{
  return back();
  return back();
}

but it doesn't seem to work.

Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57

2 Answers2

14

No, but you could use session system to save URLs of 2-3-4 pages back. Use Session:: facade or session() helper for shorter syntax:

$links = session()->has('links') ? session('links') : [];
$currentLink = request()->path(); // Getting current URI like 'category/books/'
array_unshift($links, $currentLink); // Putting it in the beginning of links array
session(['links' => $links]); // Saving links array to the session

And to use it:

return redirect(session('links')[2]); // Will redirect 2 links back
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Hi, where will I put this? which page? the previous page? sorry i'm just new in laravel. thanks! – SleepWalker Mar 08 '19 at 20:54
  • 1
    @Lito - for example in a middleware ( https://laravel.com/docs/master/middleware ). Remember to put this middleware inside kernel.php file inside the $middlewareGroups array in the 'web' key, to avoid problems with session not started yet ( https://stackoverflow.com/questions/29797952/session-not-working-in-middleware-laravel-5 ). – konrados Sep 30 '19 at 15:54
3

it works for me Redirect::to($request->request->get('http_referrer'))

Labb Avdiu
  • 211
  • 3
  • 3
  • 1
    Hi! while this answer may solve OP's problem, it is discouraged to post code only answers on SO. Providing some explanation will help OP understand this solution better, while also contributing to SO's mission of providing quality solutions to future users of the site. Thanks! – d_kennetz Mar 22 '19 at 17:46