Coder Social home page Coder Social logo

ziggy's Introduction

Ziggy - Use your Laravel 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() function that works like Laravel's, making it a breeze to use your named Laravel routes in JavaScript.

Installation

Install Ziggy in your Laravel app with Composer:

composer require tightenco/ziggy

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

By default, the output of the @routes Blade directive includes a list of all your application's routes and their parameters. This route list is included in the HTML of the page and can be viewed by end users. To configure which routes are included in this list, or to show and hide different routes on different pages, see Filtering Routes.

Usage

route() function

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

Basic usage

Route::get('posts', fn (Request $request) => /* ... */)->name('posts.index');
route('posts.index'); // 'https://ziggy.test/posts'

Parameters

Route::get('posts/{post}', fn (Post $post) => /* ... */)->name('posts.show');
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'

Multiple parameters

Route::get('venues/{venue}/events/{event}', fn (Venue $venue, Event $event) => /* ... */)
    ->name('venues.events.show');
route('venues.events.show', [1, 2]);                 // 'https://ziggy.test/venues/1/events/2'
route('venues.events.show', { venue: 1, event: 2 }); // 'https://ziggy.test/venues/1/events/2'

Query parameters

Ziggy adds arguments that don't match any named route parameters as query parameters:

Route::get('venues/{venue}/events/{event}', fn (Venue $venue, Event $event) => /* ... */)
    ->name('venues.events.show');
route('venues.events.show', {
    venue: 1,
    event: 2,
    page: 5,
    count: 10,
});
// 'https://ziggy.test/venues/1/events/2?page=5&count=10'

If you need to pass a query parameter with the same name as a route parameter, nest it under the special _query key:

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

Like Laravel, Ziggy automatically encodes boolean query parameters as integers in the query string:

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

Default parameter values

Ziggy supports default route parameter values (Laravel docs).

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

URL::defaults(['locale' => $request->user()->locale ?? 'de']);
route('posts.show', 1); // 'https://ziggy.test/de/posts/1'

Examples

HTTP request with axios:

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

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

Router class

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

Check the current route: route().current()

// Laravel 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

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

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

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

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

// Laravel app has only one named route, 'home'

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

Retrieve the current route params: route().params

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

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

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

Route-model binding

Ziggy supports Laravel's route-model binding, and can even recognize custom route key names. If you pass route() a JavaScript object as a route parameter, Ziggy will use the registered route-model binding keys for that route to find the correct parameter value inside the object. If no route-model binding keys are explicitly registered for a parameter, Ziggy will use the object's id key.

// app/Models/Post.php

class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}
Route::get('blog/{post}', function (Post $post) {
    return view('posts.show', ['post' => $post]);
})->name('posts.show');
const post = {
    id: 3,
    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:

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

Ziggy also supports custom keys for scoped bindings declared directly in a route definition:

Route::get('authors/{author}/photos/{photo:uuid}', fn (Author $author, Photo $photo) => /* ... */)
    ->name('authors.photos.show');
const photo = {
    uuid: '714b19e8-ac5e-4dab-99ba-34dc6fdd24a5',
    filename: 'sunset.jpg',
}

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

TypeScript

Ziggy includes TypeScript type definitions, and an Artisan command that can generate additional type definitions to enable route name and parameter autocompletion.

To generate route types, run the ziggy:generate command with the --types or --types-only option:

php artisan ziggy:generate --types

To make your IDE aware that Ziggy's route() helper is available globally, and to type it correctly, add a declaration like this in a .d.ts file somewhere in your project:

import { route as routeFn } from 'ziggy-js';

declare global {
    var route: typeof routeFn;
}

If you don't have Ziggy's NPM package installed, add the following to your jsconfig.json or tsconfig.json to load Ziggy's types from your vendor directory:

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

JavaScript frameworks

Note

Many applications don't need the additional setup described here—the @routes Blade directive makes Ziggy's route() function and config available globally, including within bundled JavaScript files.

If you are not using the @routes Blade directive, you can import Ziggy's route() function and configuration directly into JavaScript/TypeScript files.

Generating and importing Ziggy's configuration

Ziggy provides an Artisan command to output its config and routes to a file:

php artisan ziggy:generate

This command places your configuration in resources/js/ziggy.js by default, but you can customize this path by passing an argument to the Artisan command or setting the ziggy.output.path config value.

The file ziggy:generate creates looks something like this:

// resources/js/ziggy.js

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

export { Ziggy };

Importing the route() function

You can import Ziggy like any other JavaScript library. Without the @routes Blade directive Ziggy's config is not available globally, so it must be passed to the route() function manually:

import { route } from '../../vendor/tightenco/ziggy';
import { Ziggy } from './ziggy.js';

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

To simplify importing the route() function, you can create an alias to the vendor path:

// vite.config.js

export default defineConfig({
    resolve: {
        alias: {
            'ziggy-js': path.resolve('vendor/tightenco/ziggy'),
        },
    },
});

Now your imports can be shortened to:

import { route } from 'ziggy-js';

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-js';
import App from './App.vue';

createApp(App).use(ZiggyVue);

Now you can use the route() function anywhere in your Vue components and templates:

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

If you are not using the @routes Blade directive, import Ziggy's configuration too and pass it to .use():

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

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

If you're using TypeScript, you may need to add the following declaration to a .d.ts file in your project to avoid type errors when using the route() function in your Vue component templates:

declare module 'vue' {
    interface ComponentCustomProperties {
        route: typeof routeFn;
    }
}

React

Ziggy includes a useRoute() hook to make it easy to use the route() helper in your React app:

import React from 'react';
import { useRoute } from 'ziggy-js';

export default function PostsLink() {
    const route = useRoute();

    return <a href={route('posts.index')}>Posts</a>;
}

If you are not using the @routes Blade directive, import Ziggy's configuration too and pass it to useRoute():

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>;
}

You can also make the Ziggy config object available globally, so you can call useRoute() without passing Ziggy's configuration to it every time:

// app.js
import { Ziggy } from './ziggy.js';
globalThis.Ziggy = Ziggy;

SPAs or separate repos

Ziggy's route() function is 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 config file to your frontend project, or you can return Ziggy's config as JSON from an endpoint in your Laravel API (see Retrieving Ziggy's config from an API endpoint below for an example of how to set this up).

Filtering Routes

Ziggy supports filtering the list of routes it outputs, which is useful if you have certain routes that you don't want to be included and visible in your HTML source.

Important

Hiding routes from Ziggy's output is not a replacement for thorough authentication and authorization. Routes that should not be accessibly publicly should be protected by authentication whether they're filtered out of Ziggy's output or not.

Including/excluding routes

To set up route filtering, create a config file in your Laravel app at config/ziggy.php and add either an only or except key containing 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 use asterisks as wildcards in route filters. In the example below, admin.* will exclude routes named admin.login, admin.register, etc.:

// config/ziggy.php

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

Filtering with 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 fix this, set up your Laravel app's trusted proxies 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 to the @routes directive and it will be added to Ziggy's script tag:

@routes(nonce: 'your-nonce-here')

Disabling the route() helper

If you only want to use the @routes directive to make Ziggy's configuration available in JavaScript, but don't need the route() helper function, set the ziggy.skip-route-function config to true.

Retrieving Ziggy's config from an API endpoint

If you need to retrieve Ziggy's config from your Laravel backend over the network, you can create a route that looks something like this:

// routes/api.php

use Tighten\Ziggy\Ziggy;

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

Re-generating the routes file when your app routes change

If you are generating your Ziggy config as a file by running php artisan ziggy:generate, you may want to re-run that command when your app's route files change. 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. See #655 for a Vite example.

Laravel Mix plugin 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.

ziggy's People

Contributors

alexmccabe avatar ankurk91 avatar bakerkretzmar avatar benallfree avatar ctf0 avatar d13r avatar danielcoulbourne avatar dependabot[bot] avatar driftingly avatar emielmolenaar avatar faxblaster avatar gms8994 avatar jakebathman avatar jared0430 avatar jaulz avatar livijn avatar mattkelliher avatar mattstauffer avatar mhelaiwa avatar nanaya avatar nhedger avatar rodrigopedra avatar romeromsk avatar s-widerberg avatar shuvroroy avatar svenluijten avatar thoresuenert avatar tofandel avatar victorlap avatar yeejiawei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ziggy's Issues

route() helper returns object

Hi,
The route helper is returning an object containing the route informations, i'm not able to generate a route. Am I missing something?

ps: I'm using ziggy version 0.4.1.
Iaravel v5.4.36
laravel-mix to compile react assets

Get full url

Is there a way to get the full URL (like the Laravel helper does) instead of a relative URL (like this package does)?

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"
}

Test in Laravel 5.5

I think we should be okay, but I saw some changes to getRoutesByName() so I may need to change some things for Laravel 5.5.

Anyone have a good versioning strategy to have a LTS version that works with 5.4?

Ziggy Error: "" key is required for a route

This is my actual code in javascript

    axios_get(route('User.edit', 1), function(data) {
      console.log(data);
    })

and I'm using the resource controller in laravel 5.5

but I got this error

Ziggy Error: "User" key is required for route "User.edit"

In your code;

      return url.replace(
            /\{([^}]+)\}/gi,
            function (tag) {
                var key = tag.replace(/\{|\}/gi, '');
                if (params[key] === undefined) {
                    throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
                }
                return params[key];
            }
        );

It point to this part
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';

add config publish option

i don't think using php artisan vendor:publish --provider="..." is harder and more time consuming than creating the ziggy config file manually.

Make it possible to expose routes as an API endpoint

// routes/web.php
Route::group(['prefix' => 'whatever-i-want'], function () {
    Ziggy::route();
});

Then the client could get that and cache it for a short time in local storage.

Pros: Get it once, it's clean and separated, you can put it behind auth and middleware, not janking up your templates with a blade directive
Cons: Extra HTTP request, caching means it can get out of sync

Old browser doesn't support default parameter.

params = {};
the line breaks the support for old browser.

var route = function(name, params = {}, absolute = true) {

  | var domain = (namedRoutes[name].domain || baseUrl).replace(//+$/,'') + '/',
  | url = (absolute ? domain : '') + namedRoutes[name].uri.replace(/^//, ''),
  | params = typeof params !== 'object' ? [params] : params,
  | paramsArrayKey = 0;

Default parameters

9/10 of my api calls begin with the selected sport ie sports/{sport} which means I am having to repeat adding the current sport in all my axios calls.

Is there a way to provide a default params list which can then be added to with the route() function?

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.

Refactor Test Suite and Tag v0.4.0

I'll tag all the recent changes as soon as I get a little refactoring done on the test suite so I have super confidence that everything is working as expected. Probably tomorrow night.

😄

Genetare minified version of javascript

I noticed that it generates a really big javascript code, I was wondering if it's not possible to generate a minified version for production like webpack does and it would also "protect" a little bit.

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.

Optional parameters issue

Hi,

I small issue I bumped in today: I have the following route:

Route::get('players/{season?}', 'PlayersController@index')->name('players.index');

When trying to use it with Ziggy, even when sending the season parameter, it expects me to send it as season? (and it actually works when sending it as season?!). When not sending the season parameter I'm getting the very same error.

Uncaught Ziggy Error: "season?" key is required for route "players.index"

align route.js Router object structure with Vue's router.push parameter

First off, awesome package!

As a suggestion, would you consider aligning the structure of the Router object with that of the object parameters that Vue Router's push method takes (attribute names)?

I realize that ziggy is front-end-framework agnostic, but I would think most developers are using Vue, especially since it's promoted by Laravel and Taylor.

This would make ziggy more consistent with Vue Router, it's aready pretty close.

Thanks!

"Cannot read property 'domain' of undefined" - Error when using put/patch/delete routes

This only occurs when using a put/patch/delete route.

For example:

Works:

route('articles.index');
route('articles.show', [1]);
route('articles.edit', [1]);

Does Not Work

route('articles.destroy');
route('articles.update', [1]);
route('articles.store');

image

Fails here:

https://github.com/tightenco/ziggy/blob/master/src/js/route.js#L2

var route = function(name, params = {}, absolute = true) {
    var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', // Here

Did version 0.5 remove support for subfolders?

My Laravel installation is in a subfolder /app/ (which I can't change at this time), but support for this seems to have been removed in version 0.5?

I can verify that version 0.4 correctly accesses my routes at

/app/route/123

whereas version 0.5 removes the /app/ part and requests

/route/123

Is this intentional, and if so is there a workaround?

Blacklist after white

it would be nice to have blacklist applied after whitelist.
this config

return [
    'whitelist' => ['api::*'],
    'blacklist' => ['api::admin*'],
];

suppose to expose all 'api::' except for 'api::admin'. but now i get just all whitelisted without exceptions.
or the other idea - to make lists include sub-lists. like

<?php
return [
    'whitelist' => [
        'api::*',
        'blacklist' => ['api::admin*']
    ],
    //    'blacklist' => ['api::admin*'],
];

by the way - great package! :)

Add an artisan command to output the javascript to a file for inclusion

In case someone wanted to add this to their build process, we could have a command:

php artisan ziggy:generate

which saves the output of the script into a file wrapped in an importable module.

We could even include a sample watcher so your build tool watches the routes files for changes and then re-runs the command when necessary.

Javascript crash in IE

Ziggy currently does not work in Internet Explorer. The following code causes an error.

vendor/tightenco/ziggy/src/js/route.js
Line 23:
return Object.assign({}, params);

TypeError: Object doesn't support property or method 'assign'

At this link, you can see that Object.assign() is indeed not supported in IE.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

A possible solution could be to use the polyfill described here. This could be added to the package.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

I have tested this locally and it works.

API on subdomain

Hi,

In my app the api is on a subdomain: api.example.com. With Ziggy in Vue, the url is outputted as http://example.com/api.example.com. Do you maybe have a solution for this?

Thanks :)

Allow importing route function (and data) instead of storing them globally

I love the idea of this package. I just wish it didn't pollute the global window namespace. Ideally, I would be able to simply import { route } from 'ziggy'; in my JS (e.g. Vue component or whatever), and it would automatically pull the data in with it, either from a locally-cached JSON file or even an API call.

It might even be possible to limit the included routes to those that are actually referenced by the route function, for cases where a project has a ton of routes. Perhaps using Webpack tree-shaking or something similar.

Keep up the good work!

Optional parameters not supported

Hi,

  • ziggy : v0.2.2
  • Laravel: v5.4.30

route() method throws error if optional parameters not passed

//routes/web.php
Route::get("/check/{id?}")->name("check")
// `id` should be optional, next line will throw error
route("check")
// works when id is passed
route("check",{id:123})

// works when id is passed (master branch)
route("check",{"id?":123})

Proposal: lets not pollute global variables

Hi,

Right now our Router class depends on these global variables

namedRoutes
baseUrl
baseProtocol
baseDomain
basePort

These variables are global and can be overwritten accidentally.
Recommended approach would be to namespace them, for example

var Ziggy = {
    namedRoutes : [],
    baseUrl:'some-url',
   /* other properties */
};

Thanks.

Add Contribution Guidelines

Things to include:

  • test guidelines
  • commit message naming style-guide
  • protocol for opening an issue before opening a PR

Return localhost instead of the contigured domain in virtual host

Hi I tried this package, but during the implementation of the helper function route() it returns http://localhost/..

In my project I set up a Virtual Host which point to localhost address I've been working on, The OS I'm using currently is windows 10,

For Example

  getData(route('ajax.get.event.list'), id, function(data) {
    data = data[0];
    data = editEventData(data);
    ...

the expected output should be
http://liz.dev/users/org-adviser/get/event

the return instead is
http://localhost/users/org-adviser/get/event

Laravel Modules Design?

Hi
I just started to use a Laravel Modules because I like it better than the normal folder structure so my question is does this work with https://github.com/nWidart/laravel-modules ?
I haven't tried it myself just yet been busy doing some other stuff so if someone knows if it works please let me know other than that keep up the good work! ;)

Regards

Routes within a domain group do not work correctly

Missing Protocol

When using routes in a domain group, the domain is added by the js route() function, but there is no protocol attached, so the url returned is incorrect.

in web.php

Route::domain('example.org')->group(function() {
	Route::get('/help', function () { 
			return 'help'; 
		})
		->name('help');
});

in blade/js

route('help'); 
// returns 'example.org/help' 
//     instead of '//example.org/help' 
//             or 'http://example.org/help'

Missing Port

Another thing is that if Laravel is running under example.org:81 the php route() function adds the :81 to the url, if its the current domain.

If the current URL is 'http://example.org:81/home'

dump(route('help'));
// returns 'http://example.org:81/help'

but in JS

route('help'); 
// returns 'example.org/help' 
//     instead of '//example.org:81/help' 
//             or 'http://example.org:81/help'

'composer require' not installing actual 0.3.0

I attempted to use the filter groups, but discovered that 'composer require tightenco/ziggy' isn't pulling the same v0.3.0 that is listed on GitHub (it's pulling an earlier version that is listed as 0.3.0). Can you correct this? Thanks!

Side note, in the docs, you say to use @route('author'), but you may want to correct that to @routes('author'), to avoid confusion.

Thanks a bunch!

Add Tests

  • Test that named routes are returned correctly, etc.
  • Dusk test to ensure route() works

May you add support of querystring?

Hello. May you add support of querystring in route url? I mean something like this: example.com/search?critter=bunny&gender=female&temperament=rabid&size=large&color=red

Macro implementation

Following up from my post on twitter yesterday (https://twitter.com/dbonner1987/status/889252632023490564) and my adventures down the rabbit hole with the routing system in Laravel.

I'm now using just a single Route::macro implementation that will add filtering to routes. Security through obscurity is not smart but I got a bee in my bonnet and became a bit engrossed in getting a macro working cleanly.

What I have settled on for the time being is:

// Usage
Route::blacklist()->name('tags.index')->get('/tags', 'TagsController@index');

// Implementation
Route::macro('blacklist', function () {
    return new class($this) {
        protected $router;
        
        public function __construct($router)
        {
            $this->router = $router;
        }

        public function __call($method, $parameters)
        {
            call_user_func_array([$this->router, $method], $parameters);

            if ($method === 'name') {
                config()->set('ziggy.blacklist', array_merge(
                    config('ziggy.blacklist', []), [array_get($parameters, 0, null)]
                ));
            }

            return $this;
        }
    };
});

Currently this allows all methods chained on to blacklist to be in any order.

Looking for some thoughts on this implementation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.