Laravel makes redirection clean and expressive using its redirect()
helper. But what if you want to send your user to a specific section on a page – like https://example.com/contact#form
? That’s where withFragment()
comes in handy.
In this post, we’ll walk through how to use withFragment()
in your Laravel controller or route to redirect users with a URL fragment.
withFragment()
?The withFragment()
method appends a hash fragment to your redirect URL. It’s great when you need to:
#form
, #pricing
, #faq
)Let’s say you have a contact page at /contact
, and after a form submission, you want to redirect the user back to that page and focus on the #form
anchor.
withFragment()
Here’s a typical controller method:
use Illuminate\Http\Request;
public function submitContactForm(Request $request)
{
// Validate and process the form...
// Redirect to #form section on the contact page with a success message
return redirect()
->route('contact') // or use ->to('/contact')
->withFragment('form')
->with('success', 'Your message has been sent successfully!');
}
This will redirect the user to:
/contact#form
redirect()->to()
return redirect()
->to('/about')
->withFragment('team');
This would send users to /about#team
.
Since you’re probably using fragments in response to actions (e.g., submitting a form), it’s common to pair withFragment()
with flash messages:
return redirect()
->route('contact')
->withFragment('form')
->with('status', 'Thanks for reaching out!');
In your Blade template:
@if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
Don’t forget you can use it with named routes for cleaner code:
return redirect()
->route('home')
->withFragment('pricing');
withFragment()
appends a URL hash (like #form
) during redirect.with()
.This tiny but powerful feature in Laravel can make your UI feel more seamless and user-friendly. Perfect for contact forms, pricing sections, or FAQs!