Skip to content

Redirects

Hyper provides two approaches to redirecting users: client-side navigation through hyper()->navigate() and full-page redirects through redirect()->hyperNavigate(). Understanding when to use each approach helps you build responsive, user-friendly applications.

Client-Side Navigation

hyper()->navigate()

Use navigate() for smooth, client-side transitions without full page reloads:

php
public function store()
{
    $contact = Contact::create(signals()->validate([
        'name' => 'required',
        'email' => 'required|email'
    ]));

    return hyper()->navigate("/contacts/{$contact->id}");
}

The browser URL updates and the target page loads via AJAX, providing a fast, app-like experience. This is the recommended approach for most navigation needs in Hyper applications.

With Navigation Key

Specify a navigation key for targeted partial updates:

php
return hyper()->navigate('/dashboard', 'main');

Your dashboard controller can check for this key and return only the necessary fragments:

php
public function dashboard()
{
    if (request()->isHyperNavigate('main')) {
        return hyper()->fragment('dashboard', 'main-content', $data);
    }

    return view('dashboard', $data);
}

Query Parameter Control

Navigate with query parameters using these methods:

navigateMerge()

Merge new parameters with existing ones:

php
// Current URL: /products?category=electronics
return hyper()->navigateMerge('/products?page=2');
// Result: /products?category=electronics&page=2

// Alternative: Pass query array as first parameter
return hyper()->navigateMerge(['page' => 2]);
// Result: /products?category=electronics&page=2 (maintains current path)

navigateClean()

Navigate with a clean slate, removing all existing parameters:

php
// Current URL: /products?category=electronics&page=2
return hyper()->navigateClean('/products');
// Result: /products

navigateOnly()

Preserve only specific parameters:

php
// Current URL: /products?category=electronics&page=2&sort=price
return hyper()->navigateOnly('/products', ['category', 'sort']);
// Result: /products?category=electronics&sort=price (page removed)

navigateExcept()

Preserve all parameters except specified ones:

php
// Current URL: /products?category=electronics&page=2
return hyper()->navigateExcept('/products', ['page']);
// Result: /products?category=electronics (page removed)

Full-Page Redirects

redirect() - Standard Laravel Redirects

You can use Laravel's standard redirect() helper for full-page HTTP redirects:

php
public function logout()
{
    auth()->logout();

    return redirect('/login');
}

This performs a standard HTTP 302 redirect with full page reload.

hyper()->redirect() - Hyper-Aware Redirects

For Hyper-optimized redirects that support flash data and JavaScript-based navigation:

php
public function logout()
{
    auth()->logout();

    return hyper()->redirect('/login')
        ->with('message', 'You have been logged out');
}

This executes a JavaScript redirect (window.location = ...), which:

  • Performs a full page reload
  • Preserves session flash data
  • Works with Hyper's SSE response system
  • Bypasses client-side navigation

When to Use Full-Page Redirects

Use redirect() or hyper()->redirect() when you need:

  • Session flash messages to persist
  • Complete application state reset (logout, context switches)
  • Navigation after authentication state changes
  • Compatibility with Laravel's redirect API

Flash Data

with()

Flash data to the session before redirecting (works with both redirect() and hyper()->redirect()):

php
// Standard Laravel redirect
return redirect('/contacts')
    ->with('message', 'Contact created successfully!');

// Hyper-aware redirect
return hyper()->redirect('/contacts')
    ->with('message', 'Contact created successfully!');

The flash data is available on the next request:

blade
@if(session('message'))
    <div class="alert">{{ session('message') }}</div>
@endif

Flash Multiple Values

php
return redirect('/dashboard')
    ->with([
        'message' => 'Welcome back!',
        'lastLogin' => auth()->user()->last_login_at
    ]);

withInput()

Flash form input for re-display after validation failure:

php
public function store()
{
    try {
        signals()->validate([
            'name' => 'required',
            'email' => 'required|email'
        ]);

        // Create contact...

        return redirect('/contacts');

    } catch (ValidationException $e) {
        return hyper()->redirect('/contacts/create')
            ->withInput()
            ->withErrors($e->errors());
    }
}

withErrors()

Flash validation errors:

php
return redirect('/form')
    ->withErrors(['email' => 'This email is already taken']);

Redirect Methods

back()

Navigate to the previous page:

php
public function cancel()
{
    return redirect()->back('/fallback-url');
}

The fallback URL is used if there's no previous page or if the referrer is from an external site.

route()

Redirect to a named route:

php
return redirect()->route('contacts.index');

With Parameters

php
return redirect()->route('contacts.show', ['contact' => $contact->id]);

home()

Redirect to the home page (/):

php
return redirect()->home();

refresh()

Refresh the current page:

php
return redirect()->refresh();

intended()

Redirect to the intended URL (commonly used after login):

php
public function login()
{
    if (auth()->attempt($credentials)) {
        return redirect()->intended('/dashboard');
    }

    return redirect()->back();
}

The intended URL is stored when a user attempts to access a protected page while unauthenticated.

forceReload()

Force a hard reload, bypassing the browser cache:

php
return redirect()->forceReload(true);

Comparison: navigate() vs redirect()

hyper()->navigate()

Characteristics:

  • Client-side navigation via AJAX
  • Fast, no full page reload
  • Preserves JavaScript state
  • Supports navigation keys for partial updates
  • Does not support flash data

Use for:

  • Standard navigation within your application
  • Pagination, filtering, search results
  • Tab switching, modal navigation
  • Any navigation where speed matters
php
// ✅ Ideal use cases
return hyper()->navigate('/products');
return hyper()->navigateMerge('/products?page=2');
return hyper()->navigate('/dashboard/settings', 'sidebar');

redirect() and hyper()->redirect()

Characteristics:

  • Full-page redirect (HTTP 302 or JavaScript-based)
  • Complete page reload
  • Supports session flash data
  • Compatible with Laravel's redirect API
  • Resets application state

Use for:

  • After authentication changes (login/logout)
  • When flash messages are needed
  • After operations that change app context
  • Forms with traditional redirect-after-post pattern
php
// ✅ Ideal use cases
return hyper()->redirect('/login')->with('message', 'Logged out');
return redirect()->route('dashboard');
return hyper()->redirect('/profile')->withInput()->withErrors($errors);

Security Considerations

Same-Origin Validation

Hyper validates that redirect URLs are from the same origin for security:

php
// ✅ Safe - same origin
return hyper()->navigate('/dashboard');

// ❌ Throws exception - different origin
return hyper()->navigate('https://external-site.com/page');

Back URL Validation

The back() method verifies the referrer is from the same domain:

php
// If referrer is external, fallback URL is used
return redirect()->back('/safe-fallback');

This prevents open redirect vulnerabilities where malicious actors could redirect users to phishing sites.

Learn More