Ziggy.js - Laravel Routes in JavaScript

2.6.2 · active · verified Sun Apr 19

Ziggy provides a JavaScript `route()` function that seamlessly integrates with Laravel's named routes, enabling consistent URL generation in frontend applications. The current stable version is 2.6.2, and the package maintains an active release cadence with frequent patch and minor updates, reflecting ongoing development and support. Its core differentiator lies in its ability to dynamically expose Laravel's PHP-defined routes to the JavaScript environment via a Blade directive, eliminating the need to hardcode URLs or duplicate routing logic. This integration includes support for advanced Laravel features such as route-model binding, automatic handling of query parameters, and robust TypeScript definitions for a type-safe development experience. Ziggy aims to simplify the development of single-page applications (SPAs) and traditional frontend projects by ensuring that frontend routing logic remains synchronized with the backend.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use Ziggy's `route()` function to generate URLs for Laravel named routes in JavaScript, including handling parameters, multiple parameters, query strings, and basic route model binding. It simulates the `window.Ziggy` global configuration that Laravel injects.

declare global {
  interface Window {
    Ziggy: {
      url: string;
      port: null | number;
      defaults: Record<string, any>;
      routes: Record<string, {
        uri: string;
        methods: string[];
        bindings?: Record<string, string>;
        wheres?: Record<string, string>;
      }>;
    };
  }
}

// Simulate Ziggy configuration typically injected by Laravel's @routes Blade directive
window.Ziggy = {
    url: 'https://example.com',
    port: null,
    defaults: {},
    routes: {
        'home': { uri: '/', methods: ['GET', 'HEAD'] },
        'posts.index': { uri: 'posts', methods: ['GET', 'HEAD'] },
        'posts.show': { uri: 'posts/{post}', methods: ['GET', 'HEAD'], wheres: { post: '[^/]+' } },
        'users.profile': { uri: 'users/{user}', methods: ['GET', 'HEAD'], bindings: { user: 'id' }, wheres: { user: '[^/]+' } },
        'venues.events.show': { uri: 'venues/{venue}/events/{event}', methods: ['GET', 'HEAD'], wheres: { venue: '[^/]+', event: '[^/]+' } }
    }
};

import { route } from 'ziggy-js';

// Basic usage
console.log('Home route:', route('home').toString());
// Expected: https://example.com/

// With parameters
console.log('Post show (ID 1):', route('posts.show', { post: 1 }).toString());
// Expected: https://example.com/posts/1

// Multiple parameters
console.log('Venue 1 Event 2:', route('venues.events.show', { venue: 1, event: 2 }).toString());
// Expected: https://example.com/venues/1/events/2

// Parameters with query strings
console.log('Post show with query:', route('posts.show', { post: 1, page: 2, sort: 'asc' }).toString());
// Expected: https://example.com/posts/1?page=2&sort=asc

// Route model binding (since v2.6.0)
const user = { id: 5, name: 'Alice' }; // Simulate a Laravel model object
console.log('User profile (ID 5):', route('users.profile', user).toString());
// Expected: https://example.com/users/5

// Simplified current route check (route().current() typically uses window.location)
const isCurrentRoute = (path: string, routeName: string, params: Record<string, any>) => {
    const generatedPath = route(routeName, params, false).relative(); // Get relative path
    return path === generatedPath; // Simple path match
};
console.log(`Is '/posts/1' the current 'posts.show' route? ${isCurrentRoute('/posts/1', 'posts.show', { post: 1 })}`);
// Expected: Is '/posts/1' the current 'posts.show' route? true

view raw JSON →