如何动态定义一个路由,以在需要时选择正确的控制器 /{slug}。

huangapple go评论59阅读模式
英文:

How to define a route which chooses to right Controller on the fly /{slug}

问题

我现在正面临一个挑战,我有两个控制器使用相同的路由模式。

为了简化,假设我们有一个 BlogController 和一个 PageController。这两个控制器都有相同的路由 /{slug}

当然,在这个简单的示例中,我可以为 BlogController 的路由添加前缀 /blog/{slug},然后有两个简单的路由。但在我的情况下,这不是一个选项。两个控制器的路由肯定应该只是 /{slug},没有任何前缀或后缀。

目前,我有一个路由 / {slug},它触发一个 SlugController。在这个控制器中,我首先检查是否有一个带有此 slug 的博客记录。如果是的话,我调用 BlogController。对于 PageController 也是同样的检查。否则返回 404。

有没有更智能的方法来在 routes/web.php 中进行此检查,以确定应该为给定的 slug 使用哪个控制器?

英文:

I am currently facing the challenge, that I have the same route pattern for two Controllers.

To make it easier, let's say we have a BlogController and a PageController. Both controllers have the same route /{slug}.

Of course, in this simple example I could prefix the routes for the BlogController with /blog/{slug} and have two simple routes then. But this isn't an option in my case. Both Controller's routes should definitely be just /{slug} without any pre- / postfixes.

At the moment, I have one route /{slug} which triggers a SlugController. In this Controller I first check, if there is a Blog-record with this slug. If yes, I invoke the BlogController. Same check for PageController. Otherwise 404.

Is there any smarter way, to do this check, which Controller should be used for a given slug earlier? In the routes/web.php?

答案1

得分: 1

1 - 你可以在URL中指定类型:

website.com/page/slug
website.com/slug

2 - 你可以创建一个路由,但控制器需要有两个方法,根据表中的类型(blog或page)执行不同的方法。

3 - 第三种解决方案,我认为这是你要找的,也是你想听到的:

你可以指定相同的路由URL,并根据参数调用不同的控制器:

Route::get('/{slug}', [App\Http\Controllers\PageController::class, 'index'])->where('slug', '(about|contact|pages列表中的任何页面)');

Route::get('/{slug}', [App\Http\Controllers\BlogController::class, 'index']);
英文:

There are several solutions

1 - You can specify the type in the url

website.com/page/slug
website.com/slug

2 - You can make one route but controller 2 methods

Depending on the type in the table, if it is blog or page

3 - The third solution, and I think this is what you are looking for and want to hear

You can specify the same route url and call different controllers based on the parameter

Route::get('/{slug}', [App\Http\Controllers\PageController::class, 'index'])->where('slug', '(about|contact|any page from pages list)');

Route::get('/{slug}', [App\Http\Controllers\BlogController::class, 'index']);

huangapple
  • 本文由 发表于 2023年6月15日 04:44:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定