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
.
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') }}">
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 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'));
npm run dev
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