DEV Community

Cover image for Convention over configuration Laravel router generator
Riccardo Venturini
Riccardo Venturini

Posted on

Convention over configuration Laravel router generator

Convention over configuration is a design principle that aims to reduce the amount of decisions that developers need to make, and instead rely on sensible defaults and conventions. Laravel is a web framework that follows this principle.
Following this, I created a package that generates routes based on the path of the controllers, their name and methods.

Let's see how to do it with a practical example.

Controllers: App/Http/Controllers/SomeCategory/ProductsController.php

class ProductsController
{
    // index and __invoke defaults to #[GET]
    public function index() {...}
    #[Get]
    public function show($id) {...}
    #[Post]
    public function store(Request $request) {...}
    #[Patch]
    public function update($id, Request $request) {...}
    #[Delete]
    public function destroy($id) {...}
}
Enter fullscreen mode Exit fullscreen mode

Tho get routes ready to use, simply add the following line to routes/web.php:

Route::maze(app_path('Http/Controllers'), 'App\\Http\\Controllers');
Enter fullscreen mode Exit fullscreen mode

It goes through the paths and subdirectories and generates routes for all controllers and methods found that has the attribute Get, Post, Patch or Delete.

So that line is it's the same as writing all the routes manually as before:

Route::get('/some-category/products', 'SomeCategory\ProductsController@index')->name('some-category.products');
Route::get('/some-category/products/show/{id}', 'SomeCategory\ProductsController@show')->name('some-category.products.show');
Route::post('/some-category/products/store', 'SomeCategory\ProductsController@store')->name('some-category.products.store');
Route::patch('/some-category/products/update/{id}', 'SomeCategory\ProductsController@update')->name('some-category.products.update');
Route::delete('/some-category/products/destroy/{id}', 'SomeCategory\ProductsController@destroy')->name('some-category.products.destroy');

Enter fullscreen mode Exit fullscreen mode

See more on GitHub: https://github.com/ricventu/laravel-route-maze

Top comments (0)