bmatovu/laravel-js-routes

Laravel Javascript routes.


Keywords
javascript, routes, laravel, lumen, package
License
MIT

Documentation

Laravel JS Routes.

Build Status Scrutinizer Code Quality Code Coverage StyleCI Documentation

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

Installation

Install via Composer package manager:

composer require bmatovu/laravel-js-routes

Setup

Set application URL in the environment file; .env.

APP_URL="http://localhost:8000"

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

You should .gitignore the above auto-generated file.

Publish resources

Publish JavaScript router to resources/js

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

Using Webpack | Laravel Mix

Load JavaScript router; usually in resources/js/app.js

window.route = require('./router.js').route;

console.log(route('login'));

Using ViteJS

import { route } from './router.mjs';
window.route = route;

console.log(route('login'));

Compile JS routes

npm run dev

Usage

Sample Laravel (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.

axios.get(route('posts.index'));
// http://localhost:8000/posts

axios.get(route('posts.comments', {'post': post.id}));
// http://localhost:8000/posts/1/comments

axios.get(route('posts.comments', {'post': post.id, 'comment': comment.id}));
// http://localhost:8000/posts/1/comments/4

axios.get(route('posts.comments', {'post': post.id, 'comment': comment.id, 'page': 2, 'size': 10}));
// http://localhost:8000/posts/1/comments/4?page=2&size=10

axios.delete(route('posts.destroy', {'post': post.id}));
// http://localhost:8000/posts/1

axios.get(route('posts.index', {'published-at': '2020-09-23 16:42:12'}));
// http://localhost:8000/posts?published-at=2020-09-23%2016:42:12

axios.get(route('posts.index', {'with': ['author', 'comments']}));
// http://localhost:8000/posts?with=author,comments

axios.get(route('posts.index', {'with[0]': 'author', 'with[1]': 'comments'}));
// http://localhost:8000/posts?with[0]=author&with[1]=comments