Laravel 8 路由到控制器。SEO友好的URL结构

Geo*_*eld 2 php url url-routing laravel laravel-8

我试图弄清楚如何在 Laravel 8 项目中实现特定的 URL 结构以及实现这一目标的必要途径。我想要的是:

// Example urls to listings in the business directory.
// These urls should be routed to the directory controller.
www.domain-name.com/example-business-name-d1.html
www.domain-name.com/example-business-name-d15.html
www.domain-name.com/example-business-name-d100.html
www.domain-name.com/example-business-name-d123.html
www.domain-name.com/example-business-name-d432.html

// Example urls to articles/posts in the blog.
// These urls should be routed to the posts controller.
www.domain-name.com/example-post-name-p5.html
www.domain-name.com/example-post-name-p11.html
www.domain-name.com/example-post-name-p120.html
www.domain-name.com/example-post-name-p290.html
www.domain-name.com/example-post-name-p747.html

// We want to avoid the more traditional:
www.domain-name.com/directory/example-business-name-1.html
www.domain-name.com/blog/example-post-name-5.html
Run Code Online (Sandbox Code Playgroud)

这是因为我们不希望每个列表或博客文章的 url 中都包含字符串“directory”或“blog”。没有它,搜索引擎结果会更好。

到目前为止,我在 web.php 路由文件的底部使用了一个包罗万象的路由 {any} 来“捕获所有”到达那么远的路由。然后我操作路径提供的字符串以从 url 的末尾获取 ID 和单个字符标记。然后我有这两个变量,但可以弄清楚如何将它们传递给正确的控制器!

还是我真的很笨,有更好的方法来实现这一目标?

Route::get('{any}', function($any = null){

    // Break up the url into seperate parts.
    $pieces = explode("-", $any);
    $pieces = array_reverse($pieces);
    $piece =  $pieces[0];

    // Remove the .html
    $piece = substr($piece, 0, -5);

    // Get the two parts of the identifier.
    $id = substr($piece, 1);
    $token = substr($piece, 0, 1);

    // Call correct controller based on the token.
    switch ($token) {
        case "d":
            // HERE I WANT TO PASS THE ID ON TO THE SHOW ACTION OF THE DIRECTORY CONTROLLER 
        break;
        case "p":
            // HERE I WANT TO PASS THE ID ON TO THE SHOW ACTION OF THE POSTS CONTROLLER 
        break;
        default:
            return abort(404);
        break;
    }

});
Run Code Online (Sandbox Code Playgroud)

Ron*_*den 6

我会将路径拆分为 2 个变量 ( $slugand $id) 并将其直接传递给控制器​​。

Route::get('{slug}-d{id}.html', 'DirectoryController@show')
    ->where(['slug' => '([a-z\-]+)', 'id' => '(\d+)']);

Route::get('{slug}-p{id}.html', 'PostController@show')
    ->where(['slug' => '([a-z\-]+)', 'id' => '(\d+)']);
Run Code Online (Sandbox Code Playgroud)

在你的控制器中

class DirectoryController
{
    public function show(string $slug, int $id) {}
}

class PostController
{
    public function show(string $slug, int $id) {}
}
Run Code Online (Sandbox Code Playgroud)