exmachina / laravel-route-js
Convert laravel's route to json files to be use in Javascript.
v1.1.0
2020-08-09 08:54 UTC
Requires
- php: ^7.2
This package is not auto-updated.
Last update: 2025-04-18 10:38:57 UTC
README
Convert Laravel's routes to json
file to generate URL in Javascript
Features
- Supports Laravel 5.8.x, 6.x, and 7.x
- Allow to specify what routes to be included/excluded.
Installation
composer require exmachina/laravel-route-js
In your Laravel app/config.php
, add the service provider:
ExMachina\LaravelRouteJs\Providers\JsRoutesServiceProvider::class
Configuration
First, publish the default package's configuration:
php artisan vendor:publish --provider="ExMachina\LaravelRouteJs\Providers\JsRoutesServiceProvider"
The configuration will be published to config/route-js.php
.
Element | Type | Default | Description |
---|---|---|---|
dir |
string | resources/js/routes | Directory where the files will be saved. |
route.patterns |
array | [ ] | Routes to be included when generating route list. element type: String literals or RegExp pattern or both. |
route.exclude |
boolean | false | When set to true, exclude the routes provided in routes.patterns |
Usage
Generating the routes
php artisan js-route:generate
This command will generate 2 files, the route list(laravel-routes.json
) and the js(laravel-routes.js
) file for the functionality. The default directory is resources/js/routes
.
Options
Option | Description |
---|---|
--dir |
Directory where the files will be saved |
--routes |
Routes to be included when generating route list. String literals or RegExp pattern or both. Can have multiple options for different patterns. e.g(--routes=admin* --routes=public.index) |
--exclude |
When provided, exclude the routes provided in--routes option or routes.patterns in config/route-js.php |
--exclude-js |
Only route list will be generate. The JS file that will act upon it will be excluded. |
--append |
Append the provides ROUTES to existing route list. |
JS Usage
import Route from 'path/to/laravel-route.js';
Get URL using named route
Route.get('welcome');
Route with parameters
Parameter names will be the same in what you provided in your Laravel routes.
# This will be equivalent to laravel route entry: # Route::get('profile/{id}').name('profile.edit') Route.get('profile.edit', {id: 1}) # Laravel route: Route::post('profile/{id}/address/{address_id}').name('address.edit') Route.get('address.edit', {id: 1, address_id: 1004}) # Getting route without parsing the parameters # route entry: {'public.user': {url: 'user/{user}', parameters: ["user"]}} Route.getRawURL('public.user'); // result: /user/{user} # Changing prefix and suffix of params # getRawURL(routeName, prefix = '{', suffix = '}') Route.getRawURL('public.user', ':', ''); // result: /user/:user
Route list
You can change the route list by calling setRoutes
method of Route
instance
import Route from 'path/to/laravel-route.js'; Route.setRoutes( [ { 'route-name': 'url', parameters: []} ] )