23

In a Laravel controller I have this redirect:

    return redirect()->back();

Which returns me to my previous page (say http://domain/page). However, I want to make the page jump to a particular anchor (say #section). So ultimately this page should be opened: http://domain/page#section. How can I make this happen? I tried appending the anchor to the redirect but that doesn't work.

user32421
  • 689
  • 3
  • 8
  • 19

3 Answers3

29
return Redirect::to(URL::previous() . "#whatever");

And remember to import it at the top:

use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;

I hope this works for you!

FluxCoder
  • 1,266
  • 11
  • 22
  • 1
    Thanks!! That did it! – user32421 Oct 03 '16 at 20:27
  • 1
    The `to` function also accepts the output of the `route` function (at least in Laravel 5.5), thus this is also possible for linking to a *route* with an anchor: `return redirect()->to(route('user.edit', ['user' => $user->id]) . '#myanchorid');` (see: https://stackoverflow.com/a/41606730/2286722) – Marten Koetsier Aug 07 '18 at 20:45
  • 1
    Nice, I use your code like this : `return redirect() ->to(URL::previous() . "#anchorDocuments") ->with("status", "Le fichier a bien été enregistré.");` – Sacha Durand Apr 06 '22 at 07:59
25

You can use these helpers for laravel 5.5 and above - no imports :-)

return redirect()->to(url()->previous() . '#hash');
user3180582
  • 251
  • 3
  • 5
1

Modern and more elegant solution is using the withFragment method that adds a fragment identifier to the URL:

return redirect()->route('your_route')->withFragment('your_hash');
SlimBoy Fat
  • 71
  • 1
  • 3