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) {...}
}
Tho get routes ready to use, simply add the following line to routes/web.php
:
Route::maze(app_path('Http/Controllers'), 'App\\Http\\Controllers');
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');
See more on GitHub: https://github.com/ricventu/laravel-route-maze
Top comments (0)