Laravel Javascript routes.

v2.0.0 2020-09-23 13:57 UTC

This package is auto-updated.

Last update: 2020-10-23 14:30:42 UTC


Build Status Scrutinizer Code Quality Code Coverage StyleCI Documentation

This minimalistic package will help you access exisiting PHP routes via JavaScript.


Install via Composer package manager:

composer require bmatovu/laravel-js-routes


Set application URL in the environment file; .env.


Add application URL to base layout head meta; usually in resources/views/layouts/app.blade.php

<meta name="app-url" content="{{ config('app.url') }}">

Generate routes

php artisan js-routes:generate

Routes will be written to a json file: resources/js/routes.json

Publish resources

Publish JavaScript router to resources/js/router.js

php artisan vendor:publish --provider="Bmatovu\JsRoutes\JsRoutesServiceProvider" --tag="resources"

Load JavaScript router; usually from resources/js/bootstrap.js

var router = require('./router.js');

window.route = router.route;

Compile JS routes

npm run dev


In you routes file; web.php make sure to use named routes.

$int = '^\d+$';

Route::pattern('post', $int);
Route::pattern('comment', $int);

Route::group(['prefix' => 'posts', 'as' => 'posts.'], function () {
    Route::get('/', 'PostController@index')->name('index');
    Route::get('/{post}/comments/{comment?}', 'PostController@comments')->name('comments');
    Route::delete('/{post}', 'PostController@destroy')->name('destroy');

In JavaScript; just get the route by name.

    type: "GET",
    url: route("posts.index") 
    // http://localhost:8000/posts

    type: "GET",
    url: route("posts.index", {"published-at": "2020-09-23 16:42:12"}) 
    // http://localhost:8000/posts?published-at=2020-09-23%2016:42:12

    type: "GET",
    url: route("posts.comments", {"post":}) 
    // http://localhost:8000/posts/1/comments

    type: "GET",
    url: route("posts.comments", {"post":, "comment":}) 
    // http://localhost:8000/posts/1/comments/4

    type: "DELETE",
    url: route("posts.destroy", {"post":}) 
    // http://localhost:8000/posts/1