【发布时间】:2019-01-11 14:42:20
【问题描述】:
我想从URL 中隐藏id,我有一个包含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
在URL 中不显示id。
路线:
Route::get('store/{id}/{slug}',['as'=>'showProducts','uses'=>'FrontController@getProduct']);
HREF:
<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 的参数将不一样
【问题讨论】:
-
您可能需要在表中添加另一行,例如“slug”,以便您可以查询。你想过这个方向吗?
-
是的,最好在您的产品表中拥有一个唯一的 slug 列,这样您就可以通过其唯一的 url 分配单个产品
-
使用许多可用的 sluggable 特征之一 - laracasts.com/discuss/channels/laravel/…
-
更改 where 子句以按 slug 搜索并从路由和控制器参数中删除 id。特质包可能有助于一次性解决所有问题。
-
最好在数据库表中创建新列
slug并将URL更改为使用slug而不是id列。