如何隐藏id从url在Laravel 6?



隐藏url id

https://wallpaperaccess.in/photo/162/download-wallpaper

我想要这样的url

https://wallpaperaccess.in/photo/download-wallpaper

ImagesController.php

public function show($id, $slug = null ) {
$response = Images::findOrFail($id);
$uri = $this->request->path();
if( str_slug( $response->title ) == '' ) {
$slugUrl  = '';
} else {
$slugUrl  = '/'.str_slug( $response->title );
}
$url_image = 'photo/'.$response->id.$slugUrl;
//<<<-- * Redirect the user real page * -->>>
$uriImage     =  $this->request->path();
$uriCanonical = $url_image;
if( $uriImage != $uriCanonical ) {
return redirect($uriCanonical);
}

// Photo Details
Route::get('photo/{id}/{slug?}','ImagesController@show');

注意:数据库中没有slug列,可以用title作为slug吗?

您应该添加一个列字段slug并从title自动生成它

use IlluminateSupportStr;
$slug = Str::slug($request->input('title'), '-');

InModelsImage.php

public function getRouteKeyName()
{
return 'slug';
}

Inroutesweb.php

Route::get('photo/{image:slug}','ImagesController@show');

InappHttpControllersImagesController.php

use appModelsImage.php;
...
public function show(Image $image)
{
// controller will automatically find $image with slug in url
// $image_id = $image->id;
return view('your.view', ['image' => $image]);
}

为了在URL中使用插入符而不是id,您需要…

  1. 在表中创建一个列,用于存储段鼻涕虫。使段塞唯一的一个好方法是在末尾附加实际的id。如果你真的不想在任何地方看到id,你别无选择,你必须确保自己的鼻涕虫是唯一的(有很多方法可以实现这一点)。

这是自动创建唯一段塞的一种方法:

确保slug列是可空的,然后打开模型并添加这些方法。

它们被称为"模型事件"。

  • created在模型创建时被调用。
  • updating在你更新模型时被调用,但在它实际更新之前。

使用createdupdating应该在创建或更新Images实例时自动创建段塞。

protected static function booted()
{
parent::booted();
static::created(function (Images $images) {
$images->slug = Str::slug($images->title.'-'.$images->id);
$images->save();
});
static::updating(function (Images $images) {
$images->slug = Str::slug($images->title.'-'.$images->id);
});
}

从SEO的角度来看,当标题更改时更新段码并不是一个好的做法,所以您可能想要省略这部分(static::updating...),这取决于您。

  1. 转到您的模型并添加以下方法:
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug'; //or whatever you call the slug column
}

这样,路由器就会通过单元格而不是id来解析你的模型。

  1. 在您的路由文件中,删除id并更改段的名称以匹配您的模型名称:
Route::get('photo/{images}','ImagesController@show'); //here I'm assuming your model is Images from what I see in your controller
  1. 在控制器中,将show方法的声明更改为:
public function show(Images $images)
{
dd($images);
// if you did all this correctly, $images should be the Images corresponding to the slug in the url.
// if you did something wrong, $images will be an empty Images instance
//
//
// your code...
}

Images应改名为Image,模型不能复数。

最新更新