18

I have link :

example.com/register#register

If validation fails laravel redirects to :

example.com/register

with validation errors bit without hash url part. How I can redirect to full url with # ?

I know I can use:

Redirect::to(route('register') . '#credits')

But I want complete solution so and my :

return back();

will redirect with #.

Maybe I need to override some code ?

fico7489
  • 7,931
  • 7
  • 55
  • 89
  • 2
    You basically have three options: 1) the one you write above, 2) using a URL::previous() call, and 3) adding the hash to your form action. For some more info, please see https://laracasts.com/index.php/discuss/channels/laravel/redirect-back-with-an-anchor-tag – Joel Hinz Jul 13 '16 at 14:59

6 Answers6

17

You could create the URL first, using the route name.

$url = URL::route('route_name', ['#hash_tag']);

Redirect::to($url);

Or...

return Redirect::to(URL::previous() . "#hash_tag");
Ben Rolfe
  • 305
  • 2
  • 10
  • 3
    This solution worked like a charm! BTW, it's also possible to use a helper to achieve the same result: `redirect()->route('route_name', [ '#hash_tag' ])`. It's the same logic, just a different syntax. – Gustavo Straube Dec 12 '17 at 20:27
17

But if you want to get the proper URL where hash is the fragment part and not a parameter you should use:

redirect(route('route_name', ['some_param_for_route']). '#hash')

instead of:

redirect()->route('route_name', [ 'some_param_for_route', '#hash' ])

so to get:

http://example.com/some_param_for_route#hash

and not:

http://example.com/some_param_for_route?#hash

this way you can also chain it further like for instance:

redirect(route('route_name', ['some_param']). '#hash')->with('status', 'Profile updated!');
Picard
  • 3,745
  • 3
  • 41
  • 50
4

The best solution with Laravel 9.x

return to_route('route.name')->withFragment('#comments');
iPaat
  • 792
  • 4
  • 16
2

You could use helper:

redirect()->route('route_name', [ 'some_param_for_route', '#hash' ])
2

This is the best option as per my view and your requirement.

You should use

return back()->withFragment('#hashtag');
0

I used the following code to redirect with a hashtag or fragment

in the blade, form put the following input

<input type="hidden" name="url" value="{{Request::url()}}">

and get the URL and save it on the variable

$url = $request->url . '#comment_area';

at the end redirect to $url

return redirect($url)->with('success', 'message');

the best solution used the following code.

return redirect()->to(url()->previous())->withFragment('#comment_area')->with('success', 'message');

or

return redirect()->route('route.name')->withFragment('#comment_area');

:)