Redirecting with withFragment() in Laravel

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.


What is withFragment()?

The withFragment() method appends a hash fragment to your redirect URL. It’s great when you need to:

  • Redirect users to a section of a page (#form, #pricing, #faq)
  • Trigger JavaScript or anchor-based UI navigation
  • Improve user experience in single-page applications (SPA) or multi-section pages

Example Use Case

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.


Redirect with 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

You can also use it with redirect()->to()

return redirect()
    ->to('/about')
    ->withFragment('team');

This would send users to /about#team.


Bonus: Combine with Flash Messages

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

Use in Named Routes

Don’t forget you can use it with named routes for cleaner code:

return redirect()
    ->route('home')
    ->withFragment('pricing');

Summary

  • withFragment() appends a URL hash (like #form) during redirect.
  • Helps users land on a specific section of the page.
  • Can be combined with flash messages using 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!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Copyright © 2012 - 2025 Amirol Zolkifli. All Rights Reserved.