首页 > 解决方案 > Laravel 隐藏 url 中的 ID

问题描述

我想隐藏idURL我有包含store_id、、和字段的数据库表store_name,现在它的工作方式如下:store_citystore_zipcode

http://example.com/store/1/Cafe-Crsip-Chicago-60640

但我希望它像这样改变:

http://example.com/store/Cafe-Crsip-Chicago-60640

没有显示idURL.

路线:

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 的参数将不一样

标签: phplaravel

解决方案


我会创建一条新路线:

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 来做到这一点,但我不知道它是如何工作的。


推荐阅读