Laravel Creating Dynamic Routes to controllers from Mysql database
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Title: Efficiently Generate Dynamic Routes and Controllers from MySQL Database in Laravel
Body:
In the Laravel framework, creating dynamic routes to controllers based on data within a database can be an excellent way of optimizing code, maintaining consistency in naming conventions, and facilitating scalability. With this approach, you can have your application automatically generate appropriate routes for every page from given table information. Let's explore how you can accomplish such a task step-by-step.
1. Data Preparation: Your database needs to have the necessary data for the routes. In our case, we have a group_pages table with the structure shown above. Each row has three columns (id, name, and route). The id is the unique identifier, the name is the friendly URL/route name, and the route represents the actual route path that should be used to access the page.
2. Database Connection: Before you can interact with your database, you'll need to establish a connection within your Laravel application. You can use the Database facade for this task by adding the following lines to your main configuration file (config/database.php).
```php
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
],
]
```
3. Models: Create Eloquent models for the group_pages table. This will allow you to easily interact with your database without performing direct SQL queries. You can use the Artisan command (php artisan make:model GroupPage -m) to generate the model class and its accompanying migration file. Then run 'php artisan migrate' to create the table in your application's database.
4. Model Relationship Definition: Within your models, define relationships between pages and their controllers. You can use hasOne and belongsTo relations as follows:
- **GroupPage** model:
```php
public function controller() {
return $this->hasOne(Controller::class, 'route', 'route');
}
```
- **Controller** model:
```php
public function group_page() {
return $this->belongsTo(GroupPage::class);
}
```
5. Seed Database Data: To populate your database with dummy data, you can add the following code to the DatabaseSeeder class generated by Laravel:
```php
public function run() {
$group_pages = array(
[
'name' => 'About',
'route' => 'about'
],
....
[
'name' => 'Contact',
'route' => 'contact'
]
);
foreach ($group_pages as $row) {
GroupPage::create($row);
$controller = new Controller();
$controller->setRoute($row['route']); // Set the route for each controller
$controller->save();
}
}
```
6. Dynamic Routes Generation: To generate your routes, you can use Laravel's route() method or create a custom helper function to handle it.
```php
/** @var Controller $controller */
foreach ($controllers as $controller) {
// Use Laravel's route method
Route::get($controller->route, 'Controller@index')->name('page_'.$controller->route);
// Or create a custom helper function for better readability
generateRoute($controller->route, 'Controller@index', 'page_'.$controller->route);
}
function generateRoute($route, $action, $name) {
Route::get($route, $action.'@index')->name($name);
}
```
By following these steps, you can successfully create dynamic routes and controllers from your MySQL database in Laravel. This approach simplifies the process of managing pages within your application while ensuring consistent naming conventions across routes and controllers. For a more detailed explanation and additional code examples, kindly refer to our comprehensive blog post published on https://laravelcompany.com/creating-dynamic-routes-to-controllers-from-mysql-database/.