php - Laravel 8 路由到 Controller 。 SEO 友好的 URL 结构

标签 php laravel url url-routing 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

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

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

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

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;
    }

});

最佳答案

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

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+)']);

在你的 Controller 中

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

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

关于php - Laravel 8 路由到 Controller 。 SEO 友好的 URL 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64372864/

相关文章:

php - Laravel 路由 URI : Add or condition

php - 无法让 PHP lastInsertId() 使用此设置

php - Symfony getter 和 setter 生成 - 如何忽略属性

php - 如何在 Laravel 中存储关联数组

html - "#"像这样使用时的含义 href ="#"

php - switch/cases 和 in_array 之间的循环复杂度差异

php - composer update failed 您的要求无法解析为一组可安装的软件包

javascript - 尝试发布 AJAX 请求时出现 POST 405(方法不允许)-Laravel 4

java - 尝试在 JFrame 中显示 URL 图像

jquery - 使用 jquery 获取 url 状态