Auto Route Generating (Auto-Discovery) Package for Laravel.

Overview

Laravel Auto Routes

                _              _____             _            
     /\        | |            |  __ \           | |           
    /  \  _   _| |_ ___ ______| |__) |___  _   _| |_ ___  ___ 
   / /\ \| | | | __/ _ \______|  _  // _ \| | | | __/ _ \/ __|
  / ____ \ |_| | || (_) |     | | \ \ (_) | |_| | ||  __/\__ \
 /_/    \_\__,_|\__\___/      |_|  \_\___/ \__,_|\__\___||___/

Total Downloads Latest Stable Version Latest Unstable Version License

Automatically Route Generator Package for Laravel.

Install

Supported Laravel Versions: >= 6.x

Run the following command directly in your Project path:

$ composer require izniburak/laravel-auto-routes

The service provider of the Package will be automatically discovered by Laravel.

After that, you should publish the config file via following command:

$ php artisan vendor:publish --provider="Buki\AutoRoute\AutoRouteServiceProvider"

Greate! You can start to use Auto Route Package.

Usage

Open web.php or api.php files in routes directory, and add a new route that will be generated automatically:

Route::auto('/test', 'TestController');

All methods will be automatically generated by the AutoRoute Package.

Details

  • You can use auto-route.php file in config directory in order to change configuration of the Package. You can;

    • add new patterns for the parameters of the methods.
    • change default HTTP methods.
    • change main method.
  • You can use AutoRouteFacade in web.php and api.php in order to simple code completion for the method while using an IDE or Editor. You can add the following line to top of the file:

use Buki\AutoRoute\AutoRouteFacade as Route;
  • All methods which will be auto generated must have public accessor to discovered by the AutoRoute Package.

  • If you use camelCase style for your method names in the Controllers, these methods endpoints will automatically convert to kebab-case to make pretty URLs. For example:

Route::auto('/test', 'TestController');
# OR
Route::auto('/test', TestController::class);
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL will be converted to "/test/foo-bar"
     */
    public function fooBar(Request $request)
    {
        // your codes
    }
}
  • You can specify HTTP Method for the method of the Controllers. If you want that a method works with GET method and other method works with POST method, you can do it. Just add a prefix for the method. That's all. For example;
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL: "/test/foo-bar"
     * This method will only work with 'GET' method. 
     */
    public function getFooBar(Request $request)
    {
        // your codes
    }
    
    /**
     * URL: "/test/bar-baz"
     * This method will only work with 'POST' method. 
     */
    public function postBarBaz(Request $request)
    {
        // your codes
    }
}
  • If you don't add any prefix to your methods to use HTTP method definition, all URL will work with all HTTP methods. This options can be changed from auto-route.php configuration file.

  • If you want to use snake_case format for your methods, you can do it like that:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL: "/test/foo_bar"
     * This method will only work with 'GET' method. 
     */
    public function get_foo_bar(Request $request)
    {
        // your codes
    }
    
    /**
     * URL: "/test/bar_baz"
     * This method will only work with 'POST' method. 
     */
    public function post_bar_baz(Request $request)
    {
        // your codes
    }
}
  • You can add route options via third parameter of the auto method.
Route::auto('/test', 'TestController', [
    // your options... 
]);

Options array may contain all Laravel route attributes like name, middleware, namespace, etc..

In addition, you can add patterns into the Options array in order to define new patterns for the parameters of the methods in the Controllers. For example:

Route::auto('/test', 'TestController', [
    'name' => 'test',
    'middleware' => [YourMiddleware::class],
    'patterns' => [
        'id' => '\d+',
        'value' => '\w+',
    ],
]);

According to example above, you can use $id and $value parameters in all methods in the Controller. And for these parameters, the rules you defined will be applied.

Also, to define default patterns for the parameters, you can modify patterns in auto-route.php file.

  • You can specify the Routes which will be generated automatically by using only or except with options parameters. You should use method names in the Controllers. For example;
# First Example
Route::auto('/foo', 'FooController', [
    'only' => ['fooBar', 'postUpdatePost'],
]);

# Second Example
Route::auto('/bar', 'BarController', [
    'except' => ['test', 'putExample'],
]);

According to first example above, only two methods will be generated. And according to other example, all methods will be generated except two methods which specified.

  • If you don't change the main_method in configurations, your main method will be index for the Controllers. That's mean, you should be add index method into your controller to define base endpoint of the Controller. For example;
Route::auto('/test', 'TestController');
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL: "/test"
     */
    public function index(Request $request)
    {
        // your codes
    }
    
    /**
     * URL: "/test/foo-bar"
     */
    public function fooBar(Request $request)
    {
        // your codes
    }
}
  • You can use parameters as required and optional for the methods in your Controllers. For example;
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL: "/test/{id}"
     */
    public function index(Request $request, $id)
    {
        // your codes
    }
    
    /**
     * URL: "/test/foo-bar/{name}/{surname?}"
     */
    public function fooBar(Request $request, $name, $surname = null)
    {
        // your codes
    }
}

Also, you can use parameter type to use compatible pattern for the parameter. Parameter types can be int, string, float and bool. For example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * URL: "/test/{id}"
     * id parameter must be numeric.  
     */
    public function index(Request $request, int $id)
    {
        // your codes
    }
    
    /**
     * URL: "/test/foo-bar/{name}/{surname?}"
     * name and surname parameters must be string.
     */
    public function fooBar(Request $request, string $name, string $surname = null)
    {
        // your codes
    }
}

If you define patterns for these variable names in the auto-route.php configuration file, your definition will be used for the value checking.

To use int, float, string and bool patterns quickly for your parameters, you can use parameter type directly.

  • You can use subfolder definition for the Controllers. For example;
Route::auto('/test', 'Backend.TestController');
# OR
Route::auto('/test', 'Backend\\TestController');

Support

You can use Issues

izniburak's homepage

izniburak's twitter

Licence

MIT Licence

Contributing

  1. Fork it ( https://github.com/izniburak/laravel-auto-routes/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

  • izniburak İzni Burak Demirtaş - creator, maintainer
You might also like...
Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery.

FuzzDB was created to increase the likelihood of finding application security vulnerabilities through dynamic application security testing. It's the f

Middleware to use FastRoute for handler discovery

middlewares/fast-route Middleware to use FastRoute for handler discovery. Requirements PHP = 7.2 A PSR-7 http library A PSR-15 middleware dispatcher

CollectiveAccess is a web-based suite of applications providing a framework for management, description, and discovery of complex digital

README: Pawtucket2 version 1.7.14 About CollectiveAccess CollectiveAccess is a web-based suite of applications providing a framework for management, d

This library extends the 'League OAuth2 Client' library to provide OpenID Connect Discovery support for supporting providers that expose a .well-known configuration endpoint.

OpenID Connect Discovery support for League - OAuth 2.0 Client This library extends the League OAuth2 Client library to provide OpenID Connect Discove

A Laravel package that introduces a clean object based alternative to Laravel route files.
A Laravel package that introduces a clean object based alternative to Laravel route files.

Laravel Route Registrars This package introduces a clean object based way to define your routes in a Laravel application. A tutorial on the basic prem

A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

Gretel is a Laravel package for adding route-based breadcrumbs to your application.
Gretel is a Laravel package for adding route-based breadcrumbs to your application.

Gretel Laravel breadcrumbs right out of a fairy tale. Gretel is a Laravel package for adding route-based breadcrumbs to your application. Defining Bre

instagrambot ,it’s a console-based script created for autovoting (auto poll voting) and auto looking stories

instagrambot instagram bot for auto story view 3 instagrambot ,it’s a console-based script created for autovoting (auto poll voting) and auto looking

Generate Laravel route URLs from JavaScript.
Generate Laravel route URLs from JavaScript.

Laroute Laravel has some pretty sweet helper functions for generating urls/links and its auto-json-magic makes it building APIs super easy. It's my go

Quickly identify controller methods with no route in your Laravel applications.
Quickly identify controller methods with no route in your Laravel applications.

Orphan Controller Quickly identify controller methods with no route in your Laravel applications. Installation You can install the package via Compose

#️⃣  Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models
#️⃣ Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models

Using this package you can generate, save and, route Stripe-like Hash Ids for your Eloquent Models. Hash Ids are short, unique, and non-sequential, an

Checks if a laravel route is vlaid
Checks if a laravel route is vlaid

Laravel Route Checker Checks if your Laravel routes has valid controllers Installation The package should be installed as a dev dependency, as there i

A Laravel REST API backend with React/Redux, hot module reloading in development and route-level code splitting

React Laravel Boilerplate This is the boilerplate that I personally use for getting projects off the ground quickly using my favourite stack of techno

A laravel package for generating Bitly short URLs.

Laravel Bitly Package A laravel package for generating Bitly short URLs. For more information see Bitly Requirements Laravel 5.1 or later Installation

A simple Laravel package for generating download links with options such as expire time, IP restrictions, etc.

Generate download links in your Laravel applications This package allows you to generate download links for files. Once installed you can do stuff lik

Avatar Generating Package for Laravel.

Avatar Generating Package for Laravel.

Log requests and group together for aggregated statistics of route usage
Log requests and group together for aggregated statistics of route usage

Log Laravel route usage statistics Log Laravel requests and responses for statistical purposes and optionally aggregate by hours/days/months for minim

Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries
Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries

Route Map plugin for Craft CMS 3.x Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries Related: Route

Easily add sub domains to your CakePHP application using route prefixes

Easily add sub domains to your CakePHP application using route prefixes. Based on code created by chinpei215.

Comments
  • add custom type hint

    add custom type hint

    If there is another way, I apologize for this PR, but this contribution is to be able to add Model as type hint: file auto-route.php

    'patterns'     => [
        'slug'     => '([\w\-_]+)',
        'uuid'     => '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})',
        'date'     => '([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]))',
        "customer" => "App\Models\Customer",
    ],
    

    Captura de Tela 2021-05-23 às 12 54 34

    in controller

    public function getShow(Customer $customer){}
    
    opened by MarceloSantosCorrea 7
  • Child controller methods not discover correctly.

    Child controller methods not discover correctly.

    Hi,

    I got an error about child controller classes. If you have a child controller class, which extended from another controller, the library could not discover routes from class methods correctly.

    Example:

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class FooController extends Controller
    {
        protected $type = 'FooControllerClass';
    
        public function index()
        {
            return response()->json([$this->type]);
        }
    
        public function info()
        {
            return response()->json(['info' => $this->type]);
        }
    }
    
    <?php
    
    namespace App\Http\Controllers;
    
    class BarController extends FooController
    {
        protected $type = 'BarControllerClass';
    }
    

    And in routes/web.php

    Route::auto('foo', \App\Http\Controllers\FooController::class);
    Route::auto('bar', \App\Http\Controllers\BarController::class);
    

    I expected to work these codes correctly but they didn't work. The library discover all public methods in Parents of parent class like App\Http\Controllers\Controller, Illuminate\Routing\Controller.

    Now, I know the problem and I started to work on it in order to fix it urgently.

    Probably, I will release a new version for the library.

    Thanks.

    bug 
    opened by izniburak 1
Releases(v1.6.0)
Owner
İzni Burak Demirtaş
buki. software engineer & full-stack developer. #java #php #js #go #react-native #react #docker #k8s
İzni Burak Demirtaş
Middleware to use FastRoute for handler discovery

middlewares/fast-route Middleware to use FastRoute for handler discovery. Requirements PHP >= 7.2 A PSR-7 http library A PSR-15 middleware dispatcher

Middlewares 92 Aug 10, 2022
A Laravel package that introduces a clean object based alternative to Laravel route files.

Laravel Route Registrars This package introduces a clean object based way to define your routes in a Laravel application. A tutorial on the basic prem

Ollie Codes 22 Nov 25, 2022
Checks if a laravel route is vlaid

Laravel Route Checker Checks if your Laravel routes has valid controllers Installation The package should be installed as a dev dependency, as there i

Worksome 6 Dec 9, 2021
PHPRouter is an easy-to-use, fast, and flexible PHP router package with express-style routing.

PHP-Router is a modern, fast, and adaptable composer package that provides express-style routing in PHP without a framework.

Ayodeji O. 4 Oct 20, 2022
A PHP Router Package

Router A PHP Router Package Basic Concepts A router package is a utility that, once all http requests are redirected to an entry point, can configure

null 0 Aug 26, 2022
PHP routing (like laravel) (not complete yet)

PHP Router (under construction) This repository contains routing classes that enables you to define your routes similar to laravel 8 routes. Features

Kareem M. Fouad 6 Jan 16, 2022
Manage redirects using database rules. Rules are intended to be very similar to Laravel default routes, so syntax is pretty easy to comprehend.

Laravel DB redirector Manage HTTP redirections in Laravel using database Manage redirects using database rules. Rules are intended to be very similar

Vladimir Ković 12 Jul 18, 2022
An easy way to desensitize your routes in your Laravel application

The package provides an easy way to desensitize your routes in your Laravel application. In short, Desensitize makes your routes case-insensitive, so you can access any of your routes whether they are lowercase, uppercase, or both.

Waryor 2 Mar 29, 2022
route:menu gives you a beautiful route list which is friendly on smaller terminals and brings a few new features in.

Laravel Route Menu Your route:list, sir. route:menu gives you a beautiful route list which is friendly on smaller terminals and brings a few new featu

Craig Morris 60 Nov 10, 2022
A PHP client for (Spring Cloud) Netflix Eureka service registration and discovery.

PHP Netflix Eureka Client A PHP client for (Spring Cloud) Netflix Eureka service registration and discovery. Installation You can install this package

Hamid Mohayeji 72 Aug 21, 2022