php - Laravel 隐藏 url 中的 ID
问题描述
我想隐藏id
,URL
我有包含store_id
、、和字段的数据库表store_name
,现在它的工作方式如下:store_city
store_zipcode
http://example.com/store/1/Cafe-Crsip-Chicago-60640
但我希望它像这样改变:
http://example.com/store/Cafe-Crsip-Chicago-60640
没有显示id
在URL
.
路线:
Route::get('store/{id}/{slug}',['as'=>'showProducts','uses'=>'FrontController@getProduct']);
参考文献:
<a href="store/{{$store->store_id}}/{{str_replace(' ', '-', $store->store_name)}}-{{str_replace(' ', '-', $store->store_city)}}-{{$store->store_zipcode}}">
控制器:
public function getProduct(int $id, string $slug)
{
$products = Product::where(['store_id'=>$id])
->orderBy('category_id', 'asc')
->with('category','relatedproducts', 'relatedproducts.product')
->get()
->groupBy('category_id');
}
请注意,我使用 str_replace 删除 url 中的任何空格,所以如果我使用 store/{slug} 如果我使用 str_replace 修改 url,则来自 url 的参数将不一样
解决方案
我会创建一条新路线:
Route::get('store/{slug}',['as'=>'showProducts','uses'=>'FrontController@getProduct']);
将 Href 更改为:
<a href="store/{{str_replace(' ', '_', $store->store_name)}}-{{str_replace(' ', '_', $store->store_city)}}-{{$store->store_zipcode}}">
请注意,我将 str_replace 中的 - 更改为 _
然后更改控制器以查找 store_name、store_city 和 store_zipcode 而不是 store_id
类似的东西:
public function getProduct(string $slug)
{
$slugs = explode("-", str_replace('_', ' ', $slug)); // replace the _ back to spaces and separate the 3 parts of the slug
$products = Product::where([
'store_name'=>$slugs[0], 'store_city'=>$slugs[1], 'store_zipcode'=>$slugs[2]
])
->orderBy('category_id', 'asc')
->with('category','relatedproducts', 'relatedproducts.product')
->get()->groupBy('category_id');}
希望这可以帮助!
就像@waterloomatt 提到的那样,您也可以使用 laravel 给我们的 slug helper 来做到这一点,但我不知道它是如何工作的。
推荐阅读
- php - 按关键字(例如:标题或描述)值(PHP)过滤多维数组
- java - 同步的 JPA 关系
- python - 在python代码中直接读取文件并应用模块正则表达式
- aws-lambda - 尝试创建 SNS 客户端时,Micronaut 出现日志记录错误
- python - 如何在保持行顺序的同时从 Pandas DataFrame 中采样
- java - 如何将外部 SWT 库源添加到 Maven 项目?
- node.js - npm start 失败:在 FSEvent.FSWatcher._handle.onchange (internal/fs/watchers.js:135:12)
- python - 替换嵌套列表中的 'NA'
- html - 无法将我的 HTML 网站子域连接到 GCP 和 Google 域上的主域
- c# - 在 C# .NET Core 中使用 AssemblyLoadContext 限制引用运行不受信任的代码有多脆弱