payl8rdev's avatar

Default named routes relating to the route url (Laravel 9)

I was wondering if there was some default functionality in the laravel routes file (web.php or any other route file) where you could do the following:-

Route::get('pages/books/categories', 'App\Http\Controllers\Page\Book\PageBookCategoryController@index');

And named route for the above would be 'pages/books/categories'?

At the moment I am having to do the following for it to work as expected:-

Route::get('pages/books/categories', 'App\Http\Controllers\Page\Book\PageBookCategoryController@index') ->name('pages/books/categories');

Of course this gives me the named route as 'pages/books/categories'.

The only reason why I want to do the above is because I have quite a few routes and it's quite tedious to add a named route if the url for the route is exactly the same.

0 likes
4 replies
tykus's avatar

If you want a Route name, then you must name the Route. What does it benefit you to name a route the same as the URI anyway?

tykus's avatar
tykus
Best Answer
Level 104

Here's a line you could take for a walk...

// RouteServiceProvider
public function boot()
{
    \Illuminate\Routing\Route::macro('defaultName', function () {
        $this->name($this->uri);
    });
    // ... 
// routes/web.php
Route::get('pages/books/categories', 'App\Http\Controllers\Page\Book\PageBookCategoryController@index')
    ->defaultName();

The implementation of the macro is optimistic; I will guarantee there will be edge cases where it will need tweaking, but it could get you started...

2 likes

Please or to participate in this conversation.