bmatovu/laravel-js-routes

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


README

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

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

Usage

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.

$.ajax({
    type: "GET",
    url: route("posts.index") 
    // http://localhost:8000/posts
});

$.ajax({
    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
});

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

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

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