route() function is Ziggy’s primary helper for generating URLs from Laravel route names in JavaScript. It can return either a URL string or a Router instance depending on how it’s called.
Function Signature
Parameters
The name of the route to generate a URL for. If omitted or
undefined, returns a Router instance instead of a URL string.Example: 'posts.show', 'users.edit'Route parameters to fill in the route’s URI template. Can be:
- A single value (string/number) for routes with one parameter
- An array of values in parameter order
- An object with parameter names as keys
- Model objects with
idproperty or custom route key bindings
1, [1, 2], { post: 1, comment: 5 }, { post: { id: 1 } }Whether to generate an absolute URL (including the origin) or a relative path.
true: Returns full URL likehttps://example.com/posts/1false: Returns relative path like/posts/1
Optional Ziggy configuration object. If not provided, uses the global
Ziggy variable or attempts to load config from a #ziggy-routes-json script tag.Properties:url: Application URLport: Application port (ornull)defaults: Default parameter valuesroutes: Route definitions objectlocation: Override current location (for SSR)
Return Value
- When called with a route name: Returns a
stringcontaining the generated URL - When called without arguments or with
nameasundefined: Returns aRouterinstance for advanced usage
Examples
Basic Usage
Object Parameters
Query Parameters
Relative URLs
Custom Configuration
Getting a Router Instance
Error Handling
Theroute() function throws errors in the following cases:
TypeScript Support
Ziggy provides full TypeScript support with autocomplete for route names and type-checked parameters:Implementation Details
Theroute() function is a lightweight wrapper around the Router class:
- Creates a new
Routerinstance - Parses and normalizes the parameters
- Compiles the route template with the parameters
- Returns the generated URL string
Router instance directly for use with methods like current(), has(), and accessing the params property.
See Also
- Router Class - Advanced routing features
- Vue Plugin - Using Ziggy in Vue applications
- React Hook - Using Ziggy in React applications