Ziggy Documentation

repository·2.x·Indexed 26 days ago

https://github.com/tighten/ziggy

Ziggy is a JavaScript library that allows you to use Laravel named routes directly in your JavaScript code via a `route()` function that mirrors Laravel's helper. It supports route-model binding, TypeScript autocompletion, and provides dedicated integrations for Vue (ZiggyVue) and React (useRoute hook). The library includes a Router class for route inspection and an Artisan command `ziggy:generate` to export route configurations.

Tokens
5.2K
Snippets
15
Records
37
Agent score
85%

What's inside Ziggy

  1. Configure TypeScript for Ziggy

    2.x

    Ziggy provides TypeScript definitions and an Artisan command to generate autocompletion for route names and parameters.

    1. Generate route types

    Run the following command to generate type definitions:

    php artisan ziggy:generate --types

    2. Make route() globally available

    To allow your IDE to recognize the global route helper, add this to a .d.ts file:

    import { route as routeFn } from 'ziggy-js';
    
    declare global {
        var route: typeof routeFn;
    }

    3. Configure paths (if not using NPM)

    If you haven't installed the ziggy-js NPM package, add the following to your tsconfig.json or jsconfig.json to load types from your vendor directory:

    {
        "compilerOptions": {
            "paths": {
                "ziggy-js": ["./vendor/tightenco/ziggy"]
            }
        }
    }

    4. Enable strict route name checking

    To trigger a type error when calling route() with an unrecognized route name, extend the TypeConfig interface:

    declare module 'ziggy-js' {
      interface TypeConfig {
        strictRouteNames: true
      }
    }
  2. Upgrade from 0.9.x to 1.x

    2.x

    Upgrading to Ziggy v1 involves significant changes to how the route() function behaves. If you are using the @routes Blade directive and the Javascript route() helper, follow these adjustments:

    • route() with arguments returns a string: Previously, route() returned a Router instance when arguments were provided. Now, it returns a literal URL string.
      • Remove any .url() calls chained to route(...) calls that include arguments.
      • Replace .with() calls by passing parameters as the second argument to route().
      • Replace .withQuery() calls by passing query parameters in the second argument. If query parameter names collide with route parameters, nest them under a _query key.

    Note: Calls to route() with no arguments still return the Router class, so route().current() and route().params remain functional.

  3. Setup Ziggy with React

    2.x

    Use the useRoute() hook to access the route() helper in React components. If not using the @routes Blade directive, pass the Ziggy configuration to the hook. Alternatively, you can make the config available globally via globalThis.Ziggy.

    import React from 'react';
    import { useRoute } from 'ziggy-js';
    import { Ziggy } from './ziggy.js';
    
    export default function PostsLink() {
        const route = useRoute(Ziggy);
    
        return <a href={route('posts.index')}>Posts</a>;
    }
  4. Setup Ziggy with Vue

    2.x

    Ziggy provides a Vue plugin (ZiggyVue) to make the route() helper available in templates and components. If you are not using the @routes Blade directive, you must pass the Ziggy configuration to the .use() method.

    import { createApp } from 'vue';
    import { ZiggyVue } from 'ziggy-js';
    import { Ziggy } from './ziggy.js';
    import App from './App.vue';
    
    createApp(App).use(ZiggyVue, Ziggy);
  5. Upgrade from Ziggy 1.x to 2.x

    2.x

    When upgrading to version 2.x, several breaking changes in PHP and JavaScript must be addressed:

    PHP Changes

    • Namespace Change: The PHP package namespace has changed from Tightenco\Ziggy to Tighten\Ziggy. Note that the Composer package name remains tightenco/ziggy.
    • Class Method Visibility: The makeDirectory method of the CommandRouteGenerator class is now private. Overriding this method is no longer supported.
    • Requirements: Ziggy 2.x requires at least Laravel 9 and PHP 8.1.

    JavaScript Changes

    • Named Exports Only: Ziggy no longer provides a default export. You must use named imports.
      • Old: import route from 'ziggy-js'
      • New: import { route } from 'ziggy-js'
    • Framework Plugin Locations: The Vue plugin and React hook have moved to the root of the module.
      • Old Vue: import { ZiggyVue } from 'ziggy-js/vue'
      • New Vue: import { ZiggyVue } from 'ziggy-js'
      • Old React: import { Ziggy } from 'ziggy-js/react'
      • New React: import { Ziggy } from 'ziggy-js'
    • Method Removal: The deprecated check() method (e.g., route().check('home')) has been removed. Use has() instead.
  6. Use `@routes` with Content Security Policy (CSP)

    2.x
    If your CSP blocks inline scripts, you can pass a nonce to the @routes directive. Alternatively, you can output routes as plain JSON using json: true, which avoids inline script execution but requires you to manually load the Ziggy JavaScript library.
  7. Install Ziggy in Laravel

    2.x

    Install the Ziggy package via Composer to use Laravel's named routes in your JavaScript code.

    To make the route() helper function available globally in your JavaScript, add the @routes Blade directive to your main layout file. Ensure this directive is placed before your application's JavaScript assets are loaded.

    Note: By default, @routes includes all application routes and their parameters in the HTML, which is visible to end users. Use Filtering Routes to restrict this list.

    composer require tightenco/ziggy
  8. Generate Ziggy configuration file

    2.x

    If you are not using the @routes Blade directive, you can generate a static JavaScript file containing your Laravel routes and configuration using the Artisan command. By default, this file is placed in resources/js/ziggy.js.

    php artisan ziggy:generate
  9. Configure a `ziggy-js` alias in Vite

    2.x

    To avoid long relative paths when importing the route function, you can set up an alias in your vite.config.js.

    // vite.config.js
    
    export default defineConfig({
        resolve: {
            alias: {
                'ziggy-js': path.resolve('vendor/tightenco/ziggy'),
            },
        },
    });
  10. Configure Ziggy routes using only and except

    2.x
    In Ziggy v1, the whitelist and blacklist features have been renamed to only and except. Instead of using Route::only() or Route::except() macros in your PHP route files, you should define these in your config/ziggy.php file.
  11. Define route groups in Ziggy

    2.x

    You can define named groups of routes in config/ziggy.php using the groups key. These groups can then be exposed selectively using the @routes Blade directive.

    // config/ziggy.php
    
    return [
        'groups' => [
            'admin' => ['admin.*', 'users.*'],
            'author' => ['posts.*'],
        ],
    ];

    Usage in Blade:

    {{-- Expose a single group --}}
    @routes('author')
    
    {{-- Expose multiple groups --}}
    @routes(['admin', 'author'])
  12. Filter routes in Ziggy configuration

    2.x
    You can control which routes are exported to JavaScript by creating a config/ziggy.php file in your Laravel application. You can use either the only key (to include specific routes) or the except key (to exclude specific routes). Wildcards like * are supported.