How to set dynamic route prefix in laravel?

Member

by ryleigh , in category: PHP Frameworks , 10 days ago

How to set dynamic route prefix in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 9 days ago

@ryleigh 

To set a dynamic route prefix in Laravel, you can use route parameter binding in the RouteServiceProvider. Here's an example of how to do it:

  1. Open the RouteServiceProvider file located at app/Providers/RouteServiceProvider.php
  2. Inside the map() method, add the following code to dynamically set the route prefix:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
foreach (glob(base_path('routes') . '/*.php') as $file) {
    $fileName = pathinfo($file, PATHINFO_FILENAME);
    
    if ($fileName === 'web') {
        continue;
    }
    
    $prefix = str_replace('.php', '', $fileName);
    
    Route::prefix($prefix)
        ->middleware('web')
        ->namespace($this->namespace)
        ->group($file);
}


This code will loop through all PHP files in the routes directory (excluding the web.php file) and set the route prefix based on the filename of each file.

  1. Now you can create route files with dynamic names (e.g., api.php, admin.php) in the routes directory and define routes specific to each prefix.


For example, if you have a file named api.php in the routes directory, you can define routes like this:

1
Route::get('users', 'UserController@index');


This route will be accessible at /api/users because of the dynamic route prefix set in the RouteServiceProvider.


By following these steps, you can easily set a dynamic route prefix in Laravel based on the filename of your route files.