Generate Laravel route URLs from JavaScript.

Overview

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-to choice for building single-page js apps, but routing can quickly become a bit of a pain.

Wouldn't it be amazing if we could access our Laravel routes from JavaScript?

This package allows us to port our routes over to JavaScript, and gives us a bunch of very familiar helper functions to use.

Laroute in action

Installation

Install the usual composer way.

composer.json
{
	"require" : {
		"lord/laroute" : "2.*"
	}
}

n.b Laravel 4.x users, check out version 1.3.2

app/config/app.php
	...
	
	'providers' => array(
		...
		Lord\Laroute\LarouteServiceProvider::class,
	],
	
	...

Configure (optional)

Copy the packages config files.

php artisan vendor:publish --provider='Lord\Laroute\LarouteServiceProvider'
app/config/packages/lord/laroute/config.php
return [

    /*
     * The destination path for the javascript file.
     */
    'path' => 'public/js',

    /*
     * The destination filename for the javascript file.
     */
    'filename' => 'laroute',

    /*
     * The namespace for the helper functions. By default this will bind them to
     * `window.laroute`.
     */
    'namespace' => 'laroute',

    /*
     * Generate absolute URLs
     *
     * Set the Application URL in config/app.php
     */
    'absolute' => false,

    /*
     * The Filter Methode
     *
     * 'all' => All routes except "'laroute' => false"
     * 'only' => Only "'laroute' => true" routes
     * 'force' => All routes, ignored "laroute" route parameter
     */
    'filter' => 'all',

    /*
     * Action Namespace
     *
     * Set here your controller namespace (see RouteServiceProvider -> $namespace) for cleaner action calls
     * e.g. 'App\Http\Controllers'
     */
    'action_namespace' => '',

    /*
     * The path to the template `laroute.js` file. This is the file that contains
     * the ported helper Laravel url/route functions and the route data to go
     * with them.
     */
    'template' => 'vendor/lord/laroute/src/templates/laroute.js',
    
    /*
     * Appends a prefix to URLs. By default the prefix is an empty string.
    *
    */
    'prefix' => '',

];

    

Generate the laroute.js

To access the routes, we need to "port" them over to a JavaScript file:

php artisan laroute:generate

With the default configuration, this will create a public/js/laroute.js file to include in your page, or build.

<script src="/js/laroute.js"></script>

Note: You'll have to laroute:generate if you change your routes.

JavaScript Documentation

By default, all of the functions are under the laroute namespace. This documentation will stick with this convention.

action

Generate a URL for a given controller action.

/** 
 * laroute.action(action, [parameters = {}])
 *
 * action     : The action to route to.
 * parameters : Optional. key:value object literal of route parameters.
 */

laroute.action('HomeController@getIndex');

route

Generate a URL for a given named route.

/**
 * laroute.route(name, [parameters = {}])
 *
 * name       : The name of the route to route to.
 * parameters : Optional. key:value object literal of route parameters.
 */
 
 laroute.route('Hello.{planet}', { planet : 'world' });

url

Generate a fully qualified URL to the given path.

/**
 * laroute.url(name, [parameters = []])
 *
 * name       : The name of the route to route to.
 * parameters : Optional. value array of route parameters.
 */
 
 laroute.url('foo/bar', ['aaa', 'bbb']); // -> /foo/bar/aaa/bbb

link_to

Generate a html link to the given url.

/**
 * laroute.link_to(url, [title = url, attributes = {}]])
 *
 * url        : A relative url.
 * title      : Optional. The anchor text to display
 * attributes : Optional. key:value object literal of additional html attributes.
 */
 
 laroute.link_to('foo/bar', 'Foo Bar', { style : "color:#bada55;" });

link_to_route

Generate a html link to the given route.

/**
 * laroute.link_to_route(name, [title = url, parameters = {}], attributes = {}]]])
 *
 * name       : The name of the route to route to.
 * title      : Optional. The anchor text to display
 * parameters : Optional. key:value object literal of route parameters.
 * attributes : Optional. key:value object literal of additional html attributes.
 */
 
 laroute.link_to_route('home', 'Home');

link_to_action

Generate a html link to the given action.

/**
 * laroute.link_to_action(action, [title = url, parameters = {}], attributes = {}]]])
 *
 * action     : The action to route to.
 * title      : Optional. The anchor text to display
 * parameters : Optional. key:value object literal of route parameters.
 * attributes : Optional. key:value object literal of additional html attributes.
 */
 
 laroute.link_to_action('HelloController@planet', undefined, { planet : 'world' });

PHP Documentation

Ignore/Filter Routes

By default, all routes are available to laroute after a php artisan laroute:generate. However, it is sometimes desirable to have laroute ignore certain routes. You can do this by passing a laroute route option.

Route::get('/ignore-me', [
    'laroute' => false,
    'as'      => 'ignoreme',
    'uses'    => 'IgnoreController@me'
]);

Route::group(['laroute' => false], function () {
    Route::get('/groups-are-super-useful', 'GroupsController@index');
});

Licence

View the licence in this repo.

Comments
  • Use of undefined constant laroute - assumed 'laroute'

    Use of undefined constant laroute - assumed 'laroute'

    Hey,

    One last thing here which is weird. The error above is being called everytime I try and add something like {{ laroute.action('HomeController@getIndex') }} in my template navigation in the header.

    Sorry to throw up this :(

    Cheers, Mark

    opened by mdunbavan 7
  • Create the destination folder if it doesn't exist

    Create the destination folder if it doesn't exist

    Currently it crashes if the folder where the .js should be doesn't exist:

      [ErrorException]
      file_put_contents(public/builds/js/routes.js): failed to open stream: No such file or directory
    
    opened by Anahkiasen 6
  • Don't force user to pass an object

    Don't force user to pass an object

    Currently Laroute behaves the same way as the UrlGenerator, but there is one caveat. While in PHP you don't have to specify the name of the arguments, in Laroute you do:

    URL::route('users.show', 3); // foo.com/users/3
    
    laroute.route('users.show', {user: 3}); // foo.com/users/3
    laroute.route('users.show', 3); // foo.com/users/{users}?3
    

    Could this difference of behavior be fixed?

    opened by Anahkiasen 5
  • Getting generator error in laravel.

    Getting generator error in laravel.

    Hey,

    Just setting up the package on L4 and when I go to do php artisan generate:laroute I get an error. It seems like it is conflicting with Jeffrey Way's Laravel Generators maybe? This is the error:

    "[InvalidArgumentException] Command "generate:laroute" is not defined."

    Is this an error at my side?

    opened by mdunbavan 5
  • Typo in LayoutServiceProvide::registerCompiler

    Typo in LayoutServiceProvide::registerCompiler

    Hi, in Lord\Laroute\LarouteServiceProvider class line 64 in 'registerCompiler' method it should be 'Lord\Laroute\Compilers\TemplateCompiler' not 'Lord\Laroute\Compilers\Templatecompiler'. (Note the capital C in TemplateCompiler)

    opened by pedrambehroozi 4
  • This did break everything, im sorry

    This did break everything, im sorry

    https://github.com/aaronlord/laroute/pull/48

    Accidantly put host in return value

    return this.getCorrectUrl(host + uri + qs);
    

    edited to

    return this.getCorrectUrl(uri + qs);
    
    opened by martdegraaf 3
  • 5.1 compatibility

    5.1 compatibility

    I try install laroute to fresh laravel 5.1.1:

    > composer update
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Conclusion: remove laravel/framework v5.1.1
        - Installation request for lord/laroute 2.* -> satisfiable by lord/laroute[v2.0.0].
        - Conclusion: don't install laravel/framework v5.1.1
        - Conclusion: don't install laravel/framework v5.1.0
        - lord/laroute v2.0.0 requires illuminate/filesystem 5.0.* -> satisfiable by illuminate/filesystem[5.0.x-dev, v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4].
        - don't install illuminate/filesystem 5.0.x-dev|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.0|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.22|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.25|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.26|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.28|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.33|don't install laravel/framework 5.1.x-dev
        - don't install illuminate/filesystem v5.0.4|don't install laravel/framework 5.1.x-dev
        - Installation request for laravel/framework 5.1.* -> satisfiable by laravel/framework[5.1.x-dev, v5.1.0, v5.1.1].
    
    opened by slider23 3
  • Wrong Urls when in app in subdir

    Wrong Urls when in app in subdir

    If app sits in subdirectory ie: domain.com/app/api/get-users (where /app/ is the main public dir then routes are generated incorrectly pointing to domain.com/api/get-users. Generator does not look up for routes in subdirectories like usual laravel router.

    opened by yadue 3
  • Strips out optional parameters on a route if not supplied

    Strips out optional parameters on a route if not supplied

    Before if I had a route such as:

    Route::get('editor/{id?}', array(
        'as' => 'designer.edit',
        'uses' => 'Focus\FormBuilder\Controller\FormBuilderController@edit'
    ));
    

    laroute would replace the optional parameter with undefined.

    laroute.route('designer.edit'); // yields /editor/undefined
    

    However, now laroute will strip out the optional parameter.

    laroute.route('designer.edit') // yields /editor
    
    opened by stanfieldr 3
  • New release with fix for urls

    New release with fix for urls

    I pulled down the latest version of laroute and got an issue with invalid urls. I see that you have fixed this in your recent commits but have not pushed a new release for this yet. A new release with these fixes would be appreciated 👍

    opened by ventrec 2
  • Add the option to disable the action in the laroute call

    Add the option to disable the action in the laroute call

    Add the option to disable the action in the laroute call to prevent exposing the PHP class and method names

    This will close https://github.com/aaronlord/laroute/issues/58

    opened by tvbeek 1
  • Change collection type for Route Collections

    Change collection type for Route Collections

    Changes the collection type from RouteCollection to AbstractRouteCollection, which is a common ancestor of both RouteCollection and CompiledRouteCollection. Calls getRoutes to retrieve an iterable route collection instead of just passing the RouteCollection object, which enables the same functionality for both collection types.

    It looks like the phpunit check for this isn't fully implemented, but I'm able to execute the laroute:generate command with these changes and all of my routes generate successfully.

    opened by sdonchez 1
  • can't install for laravel 6.13.

    can't install for laravel 6.13.

    I am trying to install the package via composer. but received an error

    • don't install illuminate/filesystem v5.7.9|don't install laravel/framework v6.13.1

    • Installation request for laravel/framework (locked at v6.13.1, required as ^6.2) -> satisfiable by laravel/framework[v6.13.1].

    opened by khaicm-0897 5
  • Project abandoned?

    Project abandoned?

    @aaronlord

    Can you just let us know if you wish to abandon this project so that someone can fork it and continue development? I realize that technically anyone can fork it at any time, but I'd prefer not to do this if you plan on coming back.

    Thanks

    opened by nexxai 3
  • Can't upgrade to laravel 5.8

    Can't upgrade to laravel 5.8

    Please add laravel 5.8 as supported version if possible. Can't upgrade it because of the laroute please check https://pastebin.com/raw/vBn3Fs4A

    thanks in advance.

    opened by besingamkb 2
Releases(3.0.0)
Owner
Aaron Lord
Aaron Lord
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
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
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
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
route:menu gives you a beautiful route list which is friendly on smaller terminals and brings a few new features in.

Laravel Route Menu Your route:list, sir. route:menu gives you a beautiful route list which is friendly on smaller terminals and brings a few new featu

Craig Morris 60 Nov 10, 2022
Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries

Route Map plugin for Craft CMS 3.x Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries Related: Route

nystudio107 30 Mar 14, 2022
Michael Pratt 307 Dec 23, 2022
#️⃣ Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models

Using this package you can generate, save and, route Stripe-like Hash Ids for your Eloquent Models. Hash Ids are short, unique, and non-sequential, an

Yunus Emre Deligöz 88 Dec 27, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
Easily generate URLs to Minecraft avatars with the ability to switch between services

Minecraft Avatar URLs This library provides PHP utilities to generate URLs to Minecraft Avatars in different formats with the ability to easily change

Gigadrive UG 3 Aug 11, 2022
A Laravel package that introduces a clean object based alternative to Laravel route files.

Laravel Route Registrars This package introduces a clean object based way to define your routes in a Laravel application. A tutorial on the basic prem

Ollie Codes 22 Nov 25, 2022
Quickly identify controller methods with no route in your Laravel applications.

Orphan Controller Quickly identify controller methods with no route in your Laravel applications. Installation You can install the package via Compose

Ryan Chandler 16 Feb 18, 2022
Auto Route Generating (Auto-Discovery) Package for Laravel.

Laravel Auto Routes _ _____ _ /\ | | | __ \ | |

İzni Burak Demirtaş 201 Jan 1, 2023
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
Gretel is a Laravel package for adding route-based breadcrumbs to your application.

Gretel Laravel breadcrumbs right out of a fairy tale. Gretel is a Laravel package for adding route-based breadcrumbs to your application. Defining Bre

Galahad 131 Dec 31, 2022
Checks if a laravel route is vlaid

Laravel Route Checker Checks if your Laravel routes has valid controllers Installation The package should be installed as a dev dependency, as there i

Worksome 6 Dec 9, 2021
A Laravel REST API backend with React/Redux, hot module reloading in development and route-level code splitting

React Laravel Boilerplate This is the boilerplate that I personally use for getting projects off the ground quickly using my favourite stack of techno

Carwyn Stephen 174 Jan 6, 2023