1

I would like to ask, if is possible to get something like dynamic routes in Laravel. I have a personal CMS, based on modules. Each module == controller. In database, I have a table called "structure", where are stored all subsites of page. The name of item should be any, so I don't know the name of the item, because it is based on user's wishes. So article module should be named as "news", "articles", "blog" etc. I don't know. It means, I can't set the route to exact word, cause its name could be anything. This is, why I have stored this data to database. In database I have also module_name, which will point to controller.

So, if user will set for example: Blog -> module Article, I need to get route from db like this:

Route::get('/Blog/', 'ArticleController@index'); 

Both "Blog" and "Article" are stored in DB.

My problem is, I am unable to retrieve this data from DB. How should I do that, from the view of "best practices"? I tried to write

use DB; 

in top of routes/web.php, but it doesn't work. And I also think, this is code ballast.

If anyone can help me with this, I would be thankfull. Thank you

1

2 Answers 2

1

actually don't know why you want do that

are you meaning something like this

// route Route::get('/{slug}', 'RedirectController@redirect'); // RedirectController public function redirect($slug) { // in your example slug is the column name of the 'Blog' $to = \DB::table('route_table')->where('slug', $slug)->firstOrFail(); // module is the column name of Article return redirect()->action($to->module . 'Controller@index'); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Route like this, set up a wildcard

Route::get('/{name}', 'ArticleController@show'); 

Then in your controller, for index() method:

public function show($name) { //$name now is equal to whatever the user put into the route //do some database stuff with $name to fetch the proper data } 

12 Comments

@index should be a listing. change it to @show($name)
@TarekAdam Yes that would be best practices
I'm afraid it won't work. I have more modules that only articles. I need also to set routes for gallery, contact-form, static page, etc etc. What do you think?
@MegoSoft check out Route Model Binding. You're better off with the ORM than the DB:: statements.
As I'm writting. I don't know the exact names of subsites. Each module should be available on any url.
|