Laravel Auto Routes Package

Packages

July 8th, 2021

laravel-auto-routes-featured.png

Auto Routes for Laravel is a package by İzni Burak Demirtaş that generates routes from a controller using auto-discovery. It works by discovering public methods on a controller and generating routes for them:

1// routes/web.php
2Route::auto('/test', TestController::class);
3 
4//
5// Controller example
6//
7namespace App\Http\Controllers;
8 
9use Illuminate\Http\Request;
10 
11class TestController extends Controller
12{
13 /**
14 * URL: "/test" - main method
15 */
16 public function index(Request $request)
17 {
18 // controller code
19 }
20 
21 /**
22 * URL: "/test/foo-bar"
23 * This method will only work with 'GET' method.
24 */
25 public function getFooBar(Request $request)
26 {
27 // controller code
28 }
29 
30 /**
31 * URL: "/test/foo_bar"
32 * This method will only work with 'GET' method.
33 */
34 public function get_foo_bar(Request $request)
35 {
36 // controller code
37 }
38 
39 
40 /**
41 * URL: "/test/bar-baz"
42 * This method will only work with 'POST' method.
43 */
44 public function postBarBaz(Request $request)
45 {
46 // controller code
47 }
48}

The route method also takes a third argument to configure parameters and middleware:

1Route::auto('/test', TestController::class, [
2 'name' => 'test',
3 'middleware' => [YourMiddleware::class],
4 // Parameters become available to methods
5 'patterns' => [
6 'id' => '\d+',
7 'value' => '\w+',
8 ],
9]);
10 
11// Limit the methods that will define routes
12Route::auto('/foo', 'FooController', [
13 'only' => ['fooBar', 'postUpdatePost'],
14]);

While most developers are happy with Laravel's built-in routing definitions (Laravel routing is so good in my humble option), it is a unique idea with examples in the source code of working with PHP's reflection API and the Laravel router. You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.