Use your Laravel named routes in JavaScript

Overview

Ziggy - Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript

GitHub Actions Status Latest Version on Packagist Downloads on Packagist Latest Version on NPM Downloads on NPM

Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use your Laravel named routes in JavaScript.

Ziggy supports all versions of Laravel from 5.4 onward, and all modern browsers.

Installation

Install Ziggy into your Laravel app with composer require tightenco/ziggy.

Add the @routes Blade directive to your main layout (before your application's JavaScript), and the route() helper function will now be available globally!

Usage

The route() helper

Ziggy's route() helper function works like Laravel's—you can pass it the name of one of your routes, and the parameters you want to pass to the route, and it will return a URL.

Basic usage

// routes/web.php

Route::get('posts', fn (Request $request) => /* ... */)->name('posts.index');
// app.js

route('posts.index'); // 'https://ziggy.test/posts'

With parameters

// routes/web.php

Route::get('posts/{post}', fn (Request $request, Post $post) => /* ... */)->name('posts.show');
// app.js

route('posts.show', 1);           // 'https://ziggy.test/posts/1'
route('posts.show', [1]);         // 'https://ziggy.test/posts/1'
route('posts.show', { post: 1 }); // 'https://ziggy.test/posts/1'

With multiple parameters

// routes/web.php

Route::get('events/{event}/venues/{venue}', fn (Request $request, Event $event, Venue $venue) => /* ... */)->name('events.venues.show');
// app.js

route('events.venues.show', [1, 2]);                 // 'https://ziggy.test/events/1/venues/2'
route('events.venues.show', { event: 1, venue: 2 }); // 'https://ziggy.test/events/1/venues/2'

With query parameters

// routes/web.php

Route::get('events/{event}/venues/{venue}', fn (Request $request, Event $event, Venue $venue) => /* ... */)->name('events.venues.show');
// app.js

route('events.venues.show', {
    event: 1,
    venue: 2,
    page: 5,
    count: 10,
});
// 'https://ziggy.test/events/1/venues/2?page=5&count=10'

If you have a query parameter with the same name as a route parameter, nest it under a _query key:

route('events.venues.show', {
    event: 1,
    venue: 2,
    _query: {
        event: 3,
        page: 5,
    },
});
// 'https://ziggy.test/events/1/venues/2?event=3&page=5'

Like Laravel's route() helper, Ziggy automatically encodes boolean query parameters as integers in the query string:

route('events.venues.show', {
    event: 1,
    venue: 2,
    _query: {
        draft: false,
        overdue: true,
    },
});
// 'https://ziggy.test/events/1/venues/2?draft=0&overdue=1'

With default parameter values

See the Laravel documentation on default route parameter values.

// routes/web.php

Route::get('{locale}/posts/{post}', fn (Request $request, Post $post) => /* ... */)->name('posts.show');
// app/Http/Middleware/SetLocale.php

URL::defaults(['locale' => $request->user()->locale ?? 'de']);
// app.js

route('posts.show', 1); // 'https://ziggy.test/de/posts/1'

Practical AJAX example

const post = { id: 1, title: 'Ziggy Stardust' };

return axios.get(route('posts.show', post)).then((response) => response.data);

The Router class

Calling Ziggy's route() helper function with no arguments will return an instance of the JavaScript Router class, which has some other useful properties and methods.

Checking the current route: route().current()

// Route called 'events.index', with URI '/events'
// Current window URL is https://ziggy.test/events

route().current();               // 'events.index'
route().current('events.index'); // true
route().current('events.*');     // true
route().current('events.show');  // false

The current() method optionally accepts parameters as its second argument, and will check that their values also match in the current URL:

// Route called 'events.venues.show', with URI '/events/{event}/venues/{venue}'
// Current window URL is https://myapp.com/events/1/venues/2?authors=all

route().current('events.venues.show', { event: 1, venue: 2 }); // true
route().current('events.venues.show', { authors: 'all' });     // true
route().current('events.venues.show', { venue: 6 });           // false

Checking if a route exists: route().has()

// App has only one named route, 'home'

route().has('home');   // true
route().has('orders'); // false

Retrieving the current route params: route().params

// Route called 'events.venues.show', with URI '/events/{event}/venues/{venue}'
// Current window URL is https://myapp.com/events/1/venues/2?authors=all

route().params; // { event: '1', venue: '2', authors: 'all' }

Note: parameter values retrieved with route().params will always be returned as strings.

Route-model binding

Ziggy supports Laravel route-model binding, and can even recognize custom route key names. If you pass route() a JavaScript object as one of the route parameters, Ziggy will use the registered route-model binding keys for that route to find the parameter value in the object and insert it into the URL (falling back to an id key if there is one and the route-model binding key isn't present).

// app/Models/Post.php

class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}
// app/Http/Controllers/PostController.php

class PostController
{
    public function show(Request $request, Post $post)
    {
        return view('posts.show', ['post' => $post]);
    }
}
// routes/web.php

Route::get('blog/{post}', [PostController::class, 'show'])->name('posts.show');
// app.js

const post = {
    title: 'Introducing Ziggy v1',
    slug: 'introducing-ziggy-v1',
    date: '2020-10-23T20:59:24.359278Z',
};

// Ziggy knows that this route uses the 'slug' route-model binding key name:

route('posts.show', post); // 'https://ziggy.test/blog/introducing-ziggy-v1'

Ziggy also supports custom keys for scoped bindings in the route definition (requires Laravel 7+):

// routes/web.php

Route::get('authors/{author}/photos/{photo:uuid}', fn (Request $request, Author $author, Photo $photo) => /* ... */)->name('authors.photos.show');
// app.js

const photo = {
    uuid: '714b19e8-ac5e-4dab-99ba-34dc6fdd24a5',
    filename: 'sunset.jpg',
}

route('authors.photos.show', [{ id: 1, name: 'Jacob' }, photo]);
// 'https://ziggy.test/authors/1/photos/714b19e8-ac5e-4dab-99ba-34dc6fdd24a5'

TypeScript support

Unofficial TypeScript type definitions for Ziggy are maintained by benallfree as part of Definitely Typed, and can be installed with npm install @types/ziggy-js.

Advanced Setup

JavaScript frameworks

If you are not using Blade, or would prefer not to use the @routes directive, Ziggy provides an artisan command to output its config and routes to a file: php artisan ziggy:generate. By default this command stores your routes at resources/js/ziggy.js, but you can pass an argument to it to use a different path. Alternatively, you can return Ziggy's config as JSON from an endpoint in your Laravel API (see Retrieving Ziggy's routes and config from an API endpoint below for an example of how to set this up).

The file generated by php artisan ziggy:generate will look something like this:

// ziggy.js

const Ziggy = {
    routes: {"home":{"uri":"\/","methods":["GET","HEAD"],"domain":null},"login":{"uri":"login","methods":["GET","HEAD"],"domain":null}},
    url: 'http://ziggy.test',
    port: false
};

export { Ziggy };

You can optionally create a webpack alias to make importing Ziggy's core source files easier:

// webpack.mix.js

// Mix v6
const path = require('path');

mix.alias({
    ziggy: path.resolve('vendor/tightenco/ziggy/dist'), // or 'vendor/tightenco/ziggy/dist/vue' if you're using the Vue plugin
});

// Mix v5
const path = require('path');

mix.webpackConfig({
    resolve: {
        alias: {
            ziggy: path.resolve('vendor/tightenco/ziggy/dist'),
        },
    },
});

Finally, import and use Ziggy like any other JavaScript library. Because the Ziggy config object is not available globally in this setup, you'll usually have to pass it to the route() function manually:

// app.js

import route from 'ziggy';
import { Ziggy } from './ziggy';

// ...

route('home', undefined, undefined, Ziggy);

Vue

Ziggy includes a Vue plugin to make it easy to use the route() helper throughout your Vue app:

import { createApp } from 'vue';
import { ZiggyVue } from 'ziggy';
import { Ziggy } from './ziggy';
import App from './App';

createApp(App).use(ZiggyVue, Ziggy);

// Vue 2
import Vue from 'vue'
import { ZiggyVue } from 'ziggy';
import { Ziggy } from './ziggy';

Vue.use(ZiggyVue, Ziggy);

If you use this plugin with the Laravel Mix alias shown above, make sure to update the alias to vendor/tightenco/ziggy/dist/vue.

Note: If you use the @routes Blade directive in your views, Ziggy's configuration will already be available globally, so you don't need to import the Ziggy config object and pass it into use().

Now you can use route() anywhere in your Vue components and templates, like so:

<a class="nav-link" :href="route('home')">Home</a>

React

To use Ziggy with React, start by importing the route() function and your Ziggy config. Because the Ziggy config object is not available globally in this setup, you'll have to pass it to the route() function manually:

// app.js

import route from 'ziggy';
import { Ziggy } from './ziggy';

// ...

route('home', undefined, undefined, Ziggy);

We're working on adding a Hook to Ziggy to make this cleaner, but for now make sure you pass the configuration object as the fourth argument to the route() function as shown above.

Note: If you include the @routes Blade directive in your views, the route() helper will already be available globally, including in your React app, so you don't need to import route or Ziggy anywhere.

SPAs or separate repos

Ziggy's route() helper function is also available as an NPM package, for use in JavaScript projects managed separately from their Laravel backend (i.e. without Composer or a vendor directory). You can install the NPM package with npm install ziggy-js.

To make your routes available on the frontend for this function to use, you can either run php artisan ziggy:generate and add the generated routes file to your project, or you can return Ziggy's config as JSON from an endpoint in your Laravel API (see Retrieving Ziggy's routes and config from an API endpoint below for an example of how to set this up).

Then, import and use Ziggy as above:

// app.js

import route from 'ziggy-js';

import { Ziggy } from './ziggy';
// or...
const response = await fetch('/api/ziggy');
const Ziggy = await response.toJson();

// ...

route('home', undefined, undefined, Ziggy);

Filtering Routes

Ziggy supports filtering the routes it makes available to your JavaScript, which is great if you have certain routes that you don't want to be included and visible in the source of the response sent back to clients. Filtering routes is optional—by default, Ziggy includes all your application's named routes.

Basic filtering

To set up basic route filtering, create a config file in your Laravel app at config/ziggy.php and define either an only or except setting as an array of route name patterns.

Note: You have to choose one or the other. Setting both only and except will disable filtering altogether and return all named routes.

// config/ziggy.php

return [
    'only' => ['home', 'posts.index', 'posts.show'],
];

You can also use asterisks as wildcards in route filters. In the example below, admin.* will exclude routes named admin.login and admin.register:

// config/ziggy.php

return [
    'except' => ['_debugbar.*', 'horizon.*', 'admin.*'],
];

Filtering using groups

You can also define groups of routes that you want make available in different places in your app, using a groups key in your config file:

// config/ziggy.php

return [
    'groups' => [
        'admin' => ['admin.*', 'users.*'],
        'author' => ['posts.*'],
    ],
];

Then, you can expose a specific group by passing the group name into the @routes Blade directive:

{{-- authors.blade.php --}}

@routes('author')

To expose multiple groups you can pass an array of group names:

{{-- admin.blade.php --}}

@routes(['admin', 'author'])

Note: Passing group names to the @routes directive will always take precedence over your other only or except settings.

Other

TLS/SSL termination and trusted proxies

If your application is using TLS/SSL termination or is behind a load balancer or proxy, or if it's hosted on a service that is, Ziggy may generate URLs with a scheme of http instead of https, even if your app URL uses https. To avoid this happening, set up your Laravel app's TrustProxies middleware according to the documentation on Configuring Trusted Proxies.

Using @routes with a Content Security Policy

A Content Security Policy (CSP) may block inline scripts, including those output by Ziggy's @routes Blade directive. If you have a CSP and are using a nonce to flag safe inline scripts, you can pass the nonce as as the second argument to the @routes directive and it will be added to Ziggy's script tag:

// PHP ^8.0
@routes(nonce: 'your-nonce-here')

// PHP <=7.4
@routes(null, 'your-nonce-here')

Disabling the route() helper

If you only want to use the @routes directive to make your app's routes available in JavaScript, but don't need the route() helper function, set the skip-route-function config value to true:

// config/ziggy.php

return [
    'skip-route-function' => true,
];

Retrieving Ziggy's routes and config from an API endpoint

Ziggy can easily return its config object as JSON from an endpoint in your Laravel app. For example, you could set up an /api/ziggy route that looks something like this:

// routes/api.php

use Tightenco\Ziggy\Ziggy;

Route::get('api/ziggy', fn () => response()->json(new Ziggy));

Then, client-side, you could retrieve the config with an HTTP request:

// app.js

import route from 'ziggy-js';

const response = await fetch('/api/ziggy');
const Ziggy = await response.toJson();

// ...

route('home', undefined, undefined, Ziggy);

Re-generating the routes file when your app routes change

If you're exporting your Ziggy routes as a file by running php artisan ziggy:generate, you may want to watch your app's route files and re-run the command automatically whenever they're updated. The example below is a Laravel Mix plugin, but similar functionality could be achieved without Mix. Huge thanks to Nuno Rodrigues for the idea and a sample implementation!

Code example

const mix = require('laravel-mix');
const { exec } = require('child_process');

mix.extend('ziggy', new class {
    register(config = {}) {
        this.watch = config.watch ?? ['routes/**/*.php'];
        this.path = config.path ?? '';
        this.enabled = config.enabled ?? !Mix.inProduction();
    }

    boot() {
        if (!this.enabled) return;

        const command = () => exec(
            `php artisan ziggy:generate ${this.path}`,
            (error, stdout, stderr) => console.log(stdout)
        );

        command();

        if (Mix.isWatching() && this.watch) {
            ((require('chokidar')).watch(this.watch))
                .on('change', (path) => {
                    console.log(`${path} changed...`);
                    command();
                });
        };
    }
}());

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [])
    .ziggy();

Contributing

To get started contributing to Ziggy, check out the contribution guide.

Credits

Thanks to Caleb Porzio, Adam Wathan, and Jeffrey Way for help solidifying the idea.

Security

Please review our security policy on how to report security vulnerabilities.

License

Ziggy is open source software released under the MIT license. See LICENSE for more information.

Comments
  • Routes Blade Directive not being recognized

    Routes Blade Directive not being recognized

    I'm using Laravel 5.5.28 and have tightenco/ziggy 0.6.0 installed. Console output shows that tightenco/ziggy was in fact discovered.

    I've placed @routes in my base layout blade template, but it's not being rendered. Looking at the source simply shows @routes there instead of the JavaScript output I would expect.

    Am I missing something obvious? What's the best way to troubleshoot this?

    needs more info 
    opened by rorymcdaniel 44
  • Ziggy v0.4.0 & v0.4.1 returns an object instead of string

    Ziggy v0.4.0 & v0.4.1 returns an object instead of string

    I tried Ziggy in Laravel 5.5 and it is returning an object instead of the full URL of the route like so

    route('admin.articles.index')
    
    // laravel 5.4 returns
    "http://blog.dev/admin/articles"
    
    // laravel 5.5 returns
    {
      "name": "admin.articles.index",
      "urlParams": {},
      "queryParams": {},
      "absolute": true,
      "domain": "http://blog.dev/",
      "url": "admin/articles"
    }
    
    opened by the94air 32
  • How do I use the `route` function in a compiled Vue component?

    How do I use the `route` function in a compiled Vue component?

    I'm using the following code:

                    <div class="list-group" v-if="projects.length > 0">
                        <a v-for="project in projects" :href="route('api.project', {project_id: project.id})" class="list-group-item">{{ project.name }}</a>
                    </div>
    

    But I get the following error in console:

    image

    Note that both route and namedRoutes exist. I have @route above the app.js line in my layout.

    opened by simensen 27
  • Add test case for string type

    Add test case for string type

    Version 0.4.0 is no longer working for me. I rolled back to 0.3.0.

    When i run route("valid-route") in console, it returns object rather url (string). So i am adding a test case for future proofing.

    The route() method is expected to return string types if everything goes well.

    Something is wrong with existing test cases. Don't know how they get passed. May be choose a different assertion library.

    opened by ankurk91 23
  • Documentation is missing the requirement of `vendor/tightenco/ziggy/src/js/route.js`

    Documentation is missing the requirement of `vendor/tightenco/ziggy/src/js/route.js`

    Expected Behavior

    Documentation should explain that the route.js file needs to be imported from vendor/tightenco/ziggy/src/js/route.js when using the ziggy:generate artisan command.

    Current Behavior

    Not documented.

    I've put together an example for anyone that uses Laravel Mix and Vue (probably a lot of people who want to use Ziggy!)

    opened by markokeeffe 21
  • Error in render:

    Error in render: "Error: Ziggy error: 'project' parameter is required for route 'projectPage'."

    Ziggy version

    v1.2.0

    Laravel version

    7.30.4

    Description

    ziggy is incorrectly asking for a parameter being passed to the route() function

    this is especially odd because the code causing this error is nearly identical, varying only in the name of the prop array being stepped through, to a page which is working as expected

    Ziggy call and context

    route call
    
    <inertia-link :href="route('projectPage', projects(r, c))">
        <ProjectCard :project="projects(r,c)"/>
    </inertia-link>
    

    route definition in web.php

    Route::get('projects/{project:id}', [ProjectController::class, 'projectPage'])->name('projectPage'); //*
    

    projects() function which is passing the project param to the named route

        methods: {
            projects(r,c) {
                if(r > 1) {
                    var index;
                    index = ((r * 3) - (3 - (c - 1)));
                    return this.$page.props.officeProjects[index];
                }
                return this.$page.props.officeProjects[c - 1];
            }
        }
    

    officeProjects is a properly populated array of database records, and as i said, this code exists identically, except stepping though this.$page.props.schoolProjects, which is populated in the same way, yet it does not return this error on the other page and the links route to the correct page

    
    
    ### Ziggy configuration
    
    ```js
    projectPage:
        bindings:
            project: "id"
            __proto__: Object
        methods: (2) ["GET", "HEAD"]
        uri: "projects/{project}"
        __proto__: Object
    
    
    
    ### Route definition
    
    ```php
    route definition in web.php
    
    Route::get('projects/{project:id}', [ProjectController::class, 'projectPage'])->name('projectPage'); //*
    
    opened by liam-ot 19
  • Production @routes directive breaks tests that

    Production @routes directive breaks tests that "assertSeeText()"

    Expected Behavior

    Any tests that assertSeeText() and passed before should continue to pass regardless of Ziggy version.

    Current Behavior

    Ziggy 0.6 breaks all tests that assertSeeText()

    Currently installed Laravel version:

    5.6.21

    Currently installed Ziggy version

    0.6.6

    The problem?

    I think the reason this is breaking has to do with the minification that you guys now do, where @routes used to output this:

        (function webpackUniversalModuleDefinition(root, factory) {
        if(typeof exports === 'object' && typeof module === 'object')
            module.exports = factory();
        else if(typeof define === 'function' && define.amd)
            define("route", [], factory);
        else if(typeof exports === 'object')
            exports["route"] = factory();
        else
            root["route"] = factory();
    })(this, function() {
    return /******/ (function(modules) { // webpackBootstrap
    /******/    // The module cache
    /******/    var installedModules = {};
    /******/
    /******/    // The require function
    /******/    function __webpack_require__(moduleId) {
    /******/
    /******/        // Check if module is in cache
    /******/        if(installedModules[moduleId]) {
    /******/            return installedModules[moduleId].exports;
    /******/        }
    

    It now looks like this:

    !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("route",[],t):"object"==typeof exports?exports.route=t():e.route=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}}
    

    I totally prefer your newer approach, but do you know how to get it to play nice with Laravel's seeText type-tests?

    opened by benjivm 16
  • Add ability to exclude routes

    Add ability to exclude routes

    Let's say I have some super secret endpoints (/admin/whatever), I'd like to be able to exclude them from the routes that are exposed via the generated JSON.

    Maybe this can be achieved by adding a middleware, like how aaronlord/laroute does it.

    As an extension of this, it'd be neat if I could use route groups to only expose certain routes to a "named" group, so I could use @routes('admin') in my blade file(s) to only expose routes in the admin group.

    enhancement 
    opened by svenluijten 16
  • CommandRouteGenerator Urls are different from BladeRouteGenerator

    CommandRouteGenerator Urls are different from BladeRouteGenerator

    Hey,

    I am using v1.4.6 and ran into a weird issue today. At first I was wondering why my route('login') would return a "https:" url, which had the effect that I could not login or logout, etc on my local dev system without https.

    Then I started digging around what would be the issue because as far as I can see ziggy pretends to use the app.url for route generation. For testing purposes I changed my app.url to xxx.test and it seems this is only reflected in the ziggy.js created by the CommandRouteGenerator. The BladeRouteGenerator in the directive still returns "patdbv2.test" as url and I have no clue where this even comes from, its not present in my .env file, cache is cleared etc.

    Bildschirmfoto 2022-04-13 um 16 14 57

    Anyone ran into a similar issue?

    Edit: when I explicitly use the app.url via an the api endpoint like documented it works Route::get('ziggy', fn () => response()->json(new Ziggy(null, config('app.url'))));

    just calling the class will revert to something else Route::get('ziggy', fn () => response()->json(new Ziggy));

    Edit 2: it seems the change with app.url was reverted a while ago. So this make a little bit more sense now, but the question remains why does it generate https urls when https is not used / available and why is the result of both generators different?

    needs more info 
    opened by twdnhfr 15
  • feat: Add Vue3 Provide/Inject Plugin

    feat: Add Vue3 Provide/Inject Plugin

    This PR adds a new plugin for Vue3 using Ziggy via the Provide/Inject Composition API. Using the advanced Vue set up, I ran into my problem when trying to use route() in setup(). I saw a possible solution in https://github.com/tighten/ziggy/issues/454#issuecomment-906418423 but it didn't feel like a super maintainable solution, also mixins are not recommended in Vue3 anymore.

    Note: I'm not familiar with microbundles, so if anything needs to be edited in package.json, please let me know.

    For this to work, you have to update your mix alias like below:

    mix.alias({
        ziggy: path.resolve('vendor/tightenco/ziggy/dist/vue3'), 
    });
    

    and the import of ZiggyVue3:

    import { createApp } from 'vue';
    import { ZiggyVue3 } from 'ziggy';
    import { Ziggy } from './ziggy';
    import App from './App';
    
    createApp(App).use(ZiggyVue3, Ziggy);
    

    The route() helper will still be registered globally and you gain the below functionality:

    <script>
    import { inject } from 'vue';
    
    export default {
        setup() {
            const route = inject('route');
    
            const navigation = [{
                name: 'Profile',
                href: route('profile'),
                current: route().current('profile'),
            }, {
                name: 'Settings',
                href: route('settings'),
                current: route().current('settings'),
            }, {
             ...
            }];
    
            return {
                navigation,
            };
        },
    };
    </script>
    
    opened by c-fitzmaurice 15
  • Don't check domain value at route().current()

    Don't check domain value at route().current()

    Description

    I'm developing a Laravel 8 project locally and can access it via both (and many more) localhost and blahblah.test domains. I configured Laravel's APP_URL as "http://blahblah.test". And ran @php artisan ziggy:generate "resources/js/ziggy.js" via Composer post-autoload-dump script. Well, when I open the site at http://blahblah.test/ I see the correct work of route().current('dashboard') (I have this named route and it exists in resources/js/ziggy.js). But when I open http://localhost/ - the function doesn't work properly (with any named route). If I set APP_URL to "http://localhost/", the result is mirrored: works for http://localhost/ and not for http://blahblah.test/.

    I should note that I use your library in VueJS environment.

    Suggestion

    I propose to don't include domain proto, name, and port to the algorithm of route().current() to give an ability of this function to work on deployment with a lot of different domains which point to the same back-end.

    Alternatives

    Idk

    enhancement 
    opened by nevmerzhitsky 15
  • Incorrect anchor handling

    Incorrect anchor handling

    Ziggy version

    v1.4.6

    Laravel version

    v9.8.1

    Description

    Laravel's URL generator have separate algorithm for handling URL fragments (anchors?): \Illuminate\Routing\RouteUrlGenerator::addQueryString. Fragments are always appended to the end of query string and have no '=' after them.

    Ziggy lacks that handy feature. That's the difference between Laravel and Ziggy generated URLs for the same route:

    Laravel/Blade:

    route('order', [123, '#details', 'param' => 'test']);
    

    =>https://domain.com/orders/123?param=test&#details

    Ziggy:

    route('order', [123, '#details', {param: 'test'}]);
    

    =>https://domain.com/orders/123?#details=&param=test

    Ziggy call and context

    route('order', [123, '#details', {param: 'test'}]);
    

    Ziggy configuration

    {
        "url": "https://domain.com",
        "port": null,
        "defaults": {},
        "routes": {
            "order": {
                "uri": "orders/{order}",
                "methods": [
                    "GET",
                    "HEAD"
                ],
                "wheres": {
                    "order": "\\d+"
                }
            }
        }
    }
    

    Route definition

    Route::get('/orders/{order}', [OrderController::class, 'index'])->where('order', '\d+')->name('order');
    
    enhancement help wanted 
    opened by daniser 0
  • Add `useRoute()` React hook

    Add `useRoute()` React hook

    Adds a useRoute() React hook. If the Ziggy config object is available globally, usage is as simple as:

    import { useRoute } from 'ziggy-js';
    
    export default () => {
        const route = useRoute();
    
        return (
            <a href={route('home')}>Home</a>
        );
    };
    

    Closes #327.

    opened by bakerkretzmar 3
  • Mention React usage in Readme

    Mention React usage in Readme

    Description

    I struggled a lot with the usage in a React Application. The problem was that i don't want to put the @routes blade directive in the header of my application because everyone can see all routes directly if the source code is inspected.

    Due to this i wanted to go with option two to generate the Ziggy file and use it as custom Ziggy in the route() function. In the Readme i could only find the Vue solution to use a mixin for this purpose but nothing related to React.

    Suggestion

    I wrote a very small helper that did the trick for me. Maybe this one can also be mentioned in the Readme to save some time i someone has the same issue. I called the file ziggyroutes and imported it in my application in the view where i need it. Additionally the helper methods are mentioned in the function like current(), check() and url().

    import route from '../../assets/ziggyroute';
    
    console.log(route('user.login')); 
    
    import route from 'ziggy';
    import { Ziggy } from './ziggy';
    
    export default function (name, params, absolute) {
        var self = {name: name, params: params, absolute: absolute};
    
        var routeshelper = {};
        
        routeshelper.current = (name) => {
            return route(undefined, undefined, undefined, Ziggy).current(name);
        }
        routeshelper.check = (name) => {
            return route(undefined, undefined, undefined, Ziggy).check(name);
        }
        routeshelper.url = () => {
            return route(self.name, undefined, undefined, Ziggy).url();
        }
        
        return route(name, params, absolute, Ziggy);
      }
    

    If there are any improvements for the small helper please feel free to change it.

    question 
    opened by lodzen 6
Releases(v1.5.0)
  • v1.5.0(Sep 23, 2022)

    What's Changed

    • Allow null as entire params argument by @bakerkretzmar in https://github.com/tighten/ziggy/pull/582
    • Test on PHP 8.2 by @bakerkretzmar in https://github.com/tighten/ziggy/pull/584
    • Add support for negating route filter patterns with ! by @bakerkretzmar in https://github.com/tighten/ziggy/pull/559

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.6...v1.5.0

    Source code(tar.gz)
    Source code(zip)
  • v1.4.6(Apr 8, 2022)

    What's Changed

    • Use global regex instead of replaceAll by @bakerkretzmar in https://github.com/tighten/ziggy/pull/548

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.5...v1.4.6

    Source code(tar.gz)
    Source code(zip)
  • v1.4.5(Mar 25, 2022)

    What's Changed

    • Run CI on Windows by @bakerkretzmar in https://github.com/tighten/ziggy/pull/530
    • Fix: dead code by @Tofandel in https://github.com/tighten/ziggy/pull/525
    • Fix route().current() with wheres including regex start/end anchors by @bakerkretzmar in https://github.com/tighten/ziggy/pull/535
    • Just a small PR by @Tofandel in https://github.com/tighten/ziggy/pull/528
    • Bump minimist from 1.2.5 to 1.2.6 by @dependabot in https://github.com/tighten/ziggy/pull/541
    • Fix inherited custom route key name detection by @bakerkretzmar in https://github.com/tighten/ziggy/pull/540

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.4...v1.4.5

    Source code(tar.gz)
    Source code(zip)
  • v1.4.4(Mar 25, 2022)

    What's Changed

    • still encode other characters in last parameter by @rodrigopedra in https://github.com/tighten/ziggy/pull/507
    • fix: updated the route matching logic to take the wheres into account (#513) by @Tofandel in https://github.com/tighten/ziggy/pull/514
    • feat: allow custom output via formatters by @jaulz in https://github.com/tighten/ziggy/pull/483
    • feat: Add Vue3 Provide/Inject Plugin by @c-fitzmaurice in https://github.com/tighten/ziggy/pull/518

    New Contributors

    • @c-fitzmaurice made their first contribution in https://github.com/tighten/ziggy/pull/518

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.3...v1.4.4

    Source code(tar.gz)
    Source code(zip)
  • v1.4.3(Jan 28, 2022)

    What's Changed

    • fix: exclude internal parameters by @jaulz in https://github.com/tighten/ziggy/pull/482
    • Test on PHP 8.1 by @bakerkretzmar in https://github.com/tighten/ziggy/pull/484
    • Add support for not encoding slashes in wildcard last parameter by @bakerkretzmar in https://github.com/tighten/ziggy/pull/500

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.2...v1.4.3

    Source code(tar.gz)
    Source code(zip)
  • v1.4.2(Jan 28, 2022)

    What's Changed

    • Fix name transformation in current() by @djfhe in https://github.com/tighten/ziggy/pull/466

    New Contributors

    • @djfhe made their first contribution in https://github.com/tighten/ziggy/pull/466

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.1...v1.4.2

    Source code(tar.gz)
    Source code(zip)
  • v1.4.1(Jan 28, 2022)

    What's Changed

    • fix: catch undefined global Ziggy by @jaulz in https://github.com/tighten/ziggy/pull/462
    • Fix Octane caching issue by @bakerkretzmar in https://github.com/tighten/ziggy/pull/460

    Full Changelog: https://github.com/tighten/ziggy/compare/v1.4.0...v1.4.1

    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Aug 25, 2021)

  • v1.3.6(Aug 25, 2021)

  • v1.3.5(Jul 20, 2021)

  • v1.3.4(Jul 6, 2021)

  • v1.3.1(Jun 20, 2021)

  • v1.3.0(Jun 20, 2021)

  • v1.2.0(May 24, 2021)

  • v1.1.0(Apr 2, 2021)

  • v1.0.5(Feb 5, 2021)

    • Add support for appending 'extra' parameters to the query string (#390)
    • Remove source maps (#395)
    • Use Laravel's Reflector class to get model parameter class name (#396)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.4(Dec 6, 2020)

    • Fix bug where route().current() could incorrectly return true on URLs with no parameters (#377)
    • Fix several other bugs in route().current() with params (#379)
    • Revert #334, default Ziggy's url back to url('/') instead of the APP_URL environment variable (#386)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Nov 21, 2020)

  • v1.0.2(Nov 13, 2020)

  • v1.0.1(Nov 10, 2020)

  • v1.0.0(Nov 6, 2020)

  • 0.9.4(Jun 5, 2020)

  • 0.9.3(May 8, 2020)

    • Ensure Ziggy's assets are always generated in the correct location (#290)
    • Add support for passing a CSP nonce attribute to the @routes Blade directive to be set on the script tag, thanks @tminich! (#287)
    • Improve support for using Ziggy with server-side rendering, thanks @emielmolenaar! (#260)
    • Avoid resolving the Blade compiler unless necessary, thanks @axlon! (#267)
    • Use dist/js/route.js as the npm package's main target, thanks @ankurk91 and @benallfree! (#276)
    • Readme and quality-of-life improvements (#289)
    Source code(tar.gz)
    Source code(zip)
  • v0.9.2(May 1, 2020)

  • v0.9.1(Apr 24, 2020)

    This patch release includes:

    • Converting the $generated property visibility in BladeRouteGenerator from private to public (from #279, thanks @tkrause!)
    • Switch from Travis to GitHub Actions
    • Bump version of acorn to 6.4.1 (from #274, thanks @dependabot!)
    • Fix handling of null optional parameter (from #280, thanks @nanaya!)
    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Mar 2, 2020)

    Ziggy now supports all versions of Laravel from 5.4 to 7.x

    Also included:

    • A new --group option to the generated routes command (thanks @mpskovvang)
    • A small note in the docs about CSRF when using axios calls (thanks @dabernathy89)
    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Sep 3, 2019)

  • v0.7.1(Apr 26, 2019)

    Built version of v0.7.0 (sorry!)

    Release notes for v0.7.0:

    This release includes the following changes:

    • Fix current() method returning undefined if it doesn't include an optional parameter (PR #201 from @s-widerberg)
    • Optionally include middleware to routes collection, if middleware key is set in Laravel's config/ziggy (PR #199 from @jes490)
    • Fix a low severity vulnerability with the lodash package, a dependency of other packages (PR #210 from @DanielCoulbourne)
    • Fix issue #200 where current() was returning undefined for the base route (inadvertently fixed with PR #201)
    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Apr 26, 2019)

    This release includes the following changes:

    • Fix current() method returning undefined if it doesn't include an optional parameter (PR #201 from @s-widerberg)
    • Optionally include middleware to routes collection, if middleware key is set in Laravel's config/ziggy (PR #199 from @jes490)
    • Fix a low severity vulnerability with the lodash package, a dependency of other packages (PR #210 from @DanielCoulbourne)
    • Fix issue #200 where current() was returning undefined for the base route (inadvertently fixed with PR #201)
    Source code(tar.gz)
    Source code(zip)
Owner
Tighten
Tighten
Generate Laravel route URLs from JavaScript.

Laroute Laravel has some pretty sweet helper functions for generating urls/links and its auto-json-magic makes it building APIs super easy. It's my go

Aaron Lord 785 Dec 30, 2022
Laravel Javascript Validation

Laravel Javascript Validation Laravel Javascript Validation package allows to reuse your Laravel Validation Rules, Messages, FormRequest and Validator

Proengsoft 991 Jan 4, 2023
Html Minifier adalah paket simpel untuk minify output Html, Css style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda.

Laravel Html Minifier Adalah Paket simpel untuk minify HTML, Css Style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda. Alat i

:D 16 Aug 17, 2022
Transform PHP data to JavaScript.

Transform PHP Vars to JavaScript Often, you'll find yourself in situations, where you want to pass some server-side string/array/collection/whatever t

Laracasts 2.2k Jan 1, 2023
A Blade directive to export variables to JavaScript

A Blade directive to export variables to JavaScript This package contains a Blade directive to export values to JavaScript. Here's an example of how i

Spatie 546 Dec 21, 2022
A pjax middleware for Laravel

A pjax middleware for Laravel Pjax is a jQuery plugin that leverages ajax to speed up the loading time of your pages. It works by only fetching specif

Spatie 505 Dec 28, 2022
A full-stack framework for Laravel that takes the pain out of building dynamic UIs.

Laravel Livewire See the docs for everything: https://laravel-livewire.com/docs/quickstart Awesome Livewire stuff here: https://github.com/imliam/awes

Livewire 17.7k Dec 31, 2022
Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use you

Tighten 3.1k Dec 28, 2022
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Joan 9 Oct 10, 2022
CodeIgniter4 Attribute Routes. You can set Routes in Controllers as PHP8 Attributes.

CodeIgniter4 Attribute Routes This package generates a Routes File from the Attribute Routes in your Controllers. You can set routes in your Controlle

kenjis 13 Dec 27, 2022
Laravel routes from Javascript

Laravel Javascript Routes Why? I love the Laravel 4 routing system and I often use named routes like route('users.show', array('id' => 1)) to generate

Fede Isas 63 Oct 10, 2022
Improved abstraction for dealing with union and named types.

Check whether a reflection type or method accepts a given input

Spatie 26 Dec 26, 2022
A full PHP implementation of Minecraft's Named Binary Tag (NBT) format.

php-nbt A full PHP implementation of Minecraft's Named Binary Tag (NBT) format. In contrast to other implementations, this library provides full suppo

Aternos 8 Oct 7, 2022
This is a Reddit-like clone named Scroller, made for the project component of COSC 360 - Web Programming.

The COSC 360 Project Due Dates: See Milestone Dates Overview: The project is designed to help develop your skills for full stack development. With thi

null 3 Jun 30, 2022
An easy way to desensitize your routes in your Laravel application

The package provides an easy way to desensitize your routes in your Laravel application. In short, Desensitize makes your routes case-insensitive, so you can access any of your routes whether they are lowercase, uppercase, or both.

Waryor 2 Mar 29, 2022
Create your routes using attributes in your controllers

Create your routes using attributes in your controllers

Raihel 3 Jan 5, 2023
Display your Laravel routes in the console, but make it pretty. 😎

Pretty Routes for Laravel Display your Laravel routes in the console, but make it pretty. ?? Installation You can install the package via composer: co

Alex 630 Dec 30, 2022
Easily add routes to your Laravel app by creating Markdown or Blade files

Laravel Pages This package lets you create pages using Markdown or Blade without having to worry about creating routes or controllers yourself. Essent

ARCHTECH 104 Nov 12, 2022
View your Laravel routes on the browser.

View your Laravel routes on the browser. This package adds a route to your Laravel application. Once you've installed this package, enter /route-list

Patompong Savaengsuk 23 Oct 28, 2022