【问题标题】:I want to remove id from URL in my laravel我想从我的 laravel 中的 URL 中删除 id
【发布时间】:2021-12-29 04:45:53
【问题描述】:

在我的 Laravel 应用程序中,我创建了 url: like "www.example.com/rent/property-for-rent/45" 但在这里,我想从最后一个中删除 id 并将 id 与我的第二个参数连接起来,即“出租物业”,例如:“www.example.com/rent/property-for-rent-45”。

在Controller函数中获取3个参数

public function single_properties(Request $request, $property_purpose, $slug, $id)

在刀片文件中

{{url(strtolower($property->property_purpose).'/'.$property->property_slug)}}

在 Web.php 文件中

Route::get('{property_purpose}/{slug}/{id}', 'PropertiesController@single_properties');

我试图从函数、刀片和路由中减少参数,但对我不起作用。 谁能帮帮我,我被困在里面了,

【问题讨论】:

  • 错误是什么?如果 slug 中包含一个 int 怎么办?

标签: php laravel laravel-5


【解决方案1】:

你可以这样做:

public function singleProperties(Request $request, $property_purpose, $slug, $id)
{
    // old url: example.com/rent/property-for-rent/45
    // new url: example.com/rent/property-for-rent-45
    $newUrl = $property_purpose . '/' . $slug . '-' . $id;

    return view('your.view.blade', [
        'new_url' => $newUrl,
    ]);
}

在你的刀片中调用{{ $new_url }}

【讨论】:

  • 此解决方案不起作用。上层函数“SingleProperties”用于获取记录并显示为单个属性。实际上,我们根据 id 获取记录。那么,我现在该怎么办?
  • 所以你想对你获取的每条记录都这样做吗?你能告诉我一个属性的内容,它包含什么数据吗?
【解决方案2】:

您可以通过简单的方式进行操作。因为网址是这样的:-

www.example.com/rent/property-for-rent-45

路由的 URL 结构类似于:/rent/slug-id 表示 id 与 slug 连接。所以 laravel 只会将它视为完整的字符串。我们将定义它,稍后在控制器中将从 slug 中提取 id。

所以在 routes/web.php 中你可以定义如下:-

在 Web.php 文件中 Route::get('{property_purpose}/{slug}','PropertiesController@single_properties');

在刀片文件中

{{url(strtolower($property->property_purpose).'/'.$property->property_slug-$property->property_id)}}

在控制器文件中你定义如下:-

在这里,您必须使用已知的 PHP 函数解析 Slug 变量。与信息一样,您知道 id 最后出现在 - 符号之后。所以你可以分解 slug 变量并在后面取 id -

public function singleProperties(Request $request, $property_purpose, $slug)
{

$slugarr=explode('-',$slug);
$id=$slugarr[count($slugarr)+1];// As index starts from 0, for getting last you have to this

//Now you got the $id you can fetch record you want this id

}

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 2022-09-26
    • 1970-01-01
    • 2021-10-18
    • 2017-03-11
    • 2012-08-29
    • 2012-03-19
    • 1970-01-01
    • 2020-01-30
    相关资源
    最近更新 更多