【发布时间】:2020-10-07 11:01:24
【问题描述】:
在这里遇到了查询字符串/参数构建的砖墙,我觉得它不应该这么复杂,但想获得最佳实践建议。
我目前正在构建一个允许/要求用户标记其内容的社区平台。内容通过两个查询字符串参数进行标记。
请注意所有关系,包括附加/分离在内的帖子的标记逻辑已完成,这纯粹是过滤系统问题。
类别 - 帖子必须有一个类别,但只有一个类别,在搜索查询字符串时会这样附加。例如。 ?category=植物
标签 - 帖子可以(可选)有很多标签,这将附加到查询字符串中。例如。 ?tags=hardy
到目前为止。我创建了两个函数(通过 helper.php 文件)“add_query_params”和“remove_query_params”。这些很有帮助,因为它允许我添加和删除 ?category 或 ?tag 而不删除另一个。我的问题是,我似乎一辈子都无法弄清楚如何将相同标签的多个添加到查询字符串中,以允许我过滤多个参数选项!
例如
我可以建造
website.com?category=plants&tags=hardy
// I can also remove either tag without affecting the other
我无法建造
.com?category=plants&tags=hardy&tags=perenial
// (I can't add two of the same tag to the query string to allow me to filter on these in the controller/request
允许我添加/删除标签的功能如下
/**
* URL before:
* https://example.com/orders/123?order=ABC009&status=shipped
*
* 1. remove_query_params(['status'])
* 2. remove_query_params(['status', 'order'])
*
* URL after:
* 1. https://example.com/orders/123?order=ABC009
* 2. https://example.com/orders/123
*/
function remove_query_params(array $params = [])
{
$url = url()->current(); // get the base URL - everything to the left of the "?"
$query = request()->query(); // get the query parameters (what follows the "?")
foreach($params as $param) {
unset($query[$param]); // loop through the array of parameters we wish to remove and unset the parameter from the query array
}
return $query ? $url . '?' . http_build_query($query) : $url; // rebuild the URL with the remaining parameters, don't append the "?" if there aren't any query parameters left
}
/**
* URL before:
* https://example.com/orders/123?order=ABC009
*
* 1. add_query_params(['status' => 'shipped'])
* 2. add_query_params(['status' => 'shipped', 'coupon' => 'CCC2019'])
*
* URL after:
* 1. https://example.com/orders/123?order=ABC009&status=shipped
* 2. https://example.com/orders/123?order=ABC009&status=shipped&coupon=CCC2019
*/
function add_query_params(array $params = [])
{
$query = array_merge(
request()->query(),
$params
); // merge the existing query parameters with the ones we want to add
return url()->current() . '?' . http_build_query($query); // rebuild the URL with the new parameters array
}
在刀片注释中,它们会这样称呼
//Add query param
<a href="{{add_query_params(['tags' => $tag->id]) }}"
class="inline-block bg-gray-100 px-3 py-1 text-xs uppercase font-button">
#{{$tag->name}}
</a>
//Remove query param
<a href="{{remove_query_params(['category']) }}"
class="inline-block bg-gray-300 px-3 py-1 text-xs uppercase font-button">
#{{$has_category->name}}
</a>
这让我发疯了,大多数网站、电子商务、旅游网站都允许你更新查询字符串,我觉得这种方法最容易从网站的任何地方调用,并且不会被绑定到特定页面, 功能,它还使构建器可扩展和可重用于更多标签。
但我就是想不通。
任何人都对如何向查询字符串添加多个标签有任何提示或方向????
干杯
【问题讨论】:
-
在 PHP 中查询字符串数组遵循语法
tags[]=tag1&tags[]=tag2并且 laravel 确实可以使用它,或者您可以将它们作为逗号分隔传递,例如tags=tag1,tag2并将它们拆分为代码。仅此而已,可能还有其他 hacky 方法可以按照您尝试的方式进行操作,但只需使用 PHP 和 Laravel 提供的工具 -
你为什么不这样添加标签:&tags=one,two,three并用逗号展开?
标签: php html laravel post query-string