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

This package is not auto-updated.

Last update: 2024-10-04 07:55:28 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.

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

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: []} ] )