【问题标题】:Format URL query string (like Stack Overflow) with Laravel 5使用 Laravel 5 格式化 URL 查询字符串(如 Stack Overflow)
【发布时间】:2015-08-11 01:50:36
【问题描述】:

在我的网络应用程序中,我希望有帖子的 URL,就像 Stack Overflow 中的这里一样。例如:

http://mydomain/posts/214741/this-is-the-postname

但是当我写这样的路线时:

Route::get('post/{postid}/{postname}',array('as' => 'postlink', 'uses' => 'Post@singlePost'));

现在发生的情况如下:

1) 将此链接粘贴到地址栏中:

http://mydomain/en/post/214741/postname

2)按回车,由于get请求,链接变为:

http://mydomain/en/post/214741/postname?q=post%2F214741%2Fpostname

但是,我想要的是 URL 与我粘贴时的 URL 完全相同,这与在浏览器中粘贴 Stack Overflow 链接并单击 Enter 时的情况完全相同。

我需要它是一个获取请求,因为用户可以直接使用该链接,因此我的控制器需要直接从中获取信息。

使用 Laravel 处理这种情况的最佳方法是什么?

我的.htaccess 文件是:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
RewriteBase /public

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    #RewriteRule ^ index.php [L]
    RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]
</IfModule>

【问题讨论】:

  • 您问如何将 {postid} 和 {postname} 传递给 Post 控制器的 singlePost() 方法?
  • “因为它是一个获取请求,所以查询字符串将显示在链接中” - 显示什么查询字符串?不是postidpostname,确定吗?您是指提交get 表单的结果吗?
  • 是的,但我希望按照我说的那样格式化链接
  • @Mr.Phil 问题就在您的 htaccess 中。您需要删除 RewriteRule ^(.*)$ /index.php?q=$1 行,并将其替换为已注释掉的原始内容。您还应该删除 rewritebase 行,因为那可能没有帮助。为什么要更改原来的 htaccess?
  • @halfer 当然,我会立即编辑我的帖子

标签: php string url laravel get


【解决方案1】:

您的 .htaccess 看起来好像已更改为将请求的 uri 作为参数 q 的查询字符串变量传递回 index.php。

而不是这个:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?q=$1

尝试将它改回 Laravel 附带的原始版本。

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

【讨论】:

  • 这个解决方案的问题是链接现在看起来像:mydomain/en/index.php/post/214741/postname。有没有办法从 URL 中删除“index.php”?
  • 你是如何处理/en/ uri 的?我希望我的网址更像http://mydomain/index.php/en/post/214741/postnameen 目录是虚拟主机的 webroot 目录吗?
  • 是的,我在该评论中手动键入了链接,你说得对 /en/ 位于 index.php 之后。事情是我根本不希望“index.php”出现在链接中。谢谢
  • 如果可能,即使 /en/ 部分也应该删除
  • 我建议发布一个新问题。包括你的 .htaccess(人们会问)和你的路由,指明你的 webroot 是哪个目录。
【解决方案2】:

您好,您可以为 postName 变量添加一个模式

Route::get('/{postId}/{postName}', function($postId, $postName) {
  return "$postId - $postName";
})->where('postName', '.*');

你的问题发生在生产环境还是 Laravel 的开发服务器上?

【讨论】:

  • 看起来我的 htaccess 文件有问题,现在已经解决了。感谢您的意见
  • 顺便说一句,它发生在开发服务器上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 2014-05-21
  • 2013-05-11
相关资源
最近更新 更多