如何使用雄辩的可拙劣包在 Laravel 5.3 中的 url 末尾附加一个 slug?



我有 slug 雄辩包。我想创建一个这样的网址: http://www.example.com/houses/id/house-with-2-bedrooms 让我解释一下网址:

房屋和 ID 代表其余架构所述的资源和 ID。

带两间卧室的房子部分是鼻涕虫本身。 动态部分是数字 2,代表房屋拥有的卧室数量。 所以我可以

http://www.example.com/houses/100/house-with-2-bedrooms
http://www.example.com/houses/101/house-with-2-bedrooms
http://www.example.com/houses/102/house-with-3-bedrooms

我知道 slug 更常用于创建更复杂的 url,删除 url 不需要的字符,如 ~ 和 ^,但我现在只想要一个简单的字符。

我在 Git 网站上阅读了教程,但无法使其工作,也不明白我在做什么。

到目前为止,我有这个:

我的房子模型有一个蛞蝓字段。

我定义了可拙劣的特征:

我的模型:

use CviebrockEloquentSluggableSluggable;
class House extends Model
{
use Sluggable; 
public function announcement()
{           
return $this->belongsTo(AppAnnouncement::class, 'id' , 'id');  
}   
protected $table = 'house';
protected $primaryKey = 'id';
protected $fillable = array( 'id', 'capacity', 'bedrooms', 'pool', 'price', 'dir_id', 'identifier', 'photos', 'views', 'active', 'description', 'slug');
public $timestamps = false;
protected $connection = 'eloquent_db';
public function sluggable()
{
return ['slug' => ['source' => 'bedrooms'] ];
}

}

我的控制器:

route::resource('houses', HousesController'). 

你可以简单地实现这一点

在途中

Route::resource('houses', 'HousesController', ['except' => 'show']);
Route::get('/houses/{id}/{slug}', 'HousesController@show')->name('houses.show');

查看用于生成 URL 的内容

<a href="{{ route('houses.show', [$house->id, $house->slug]) }}">Sample House</a>

在你的模型中创建一个函数作为你想要显示的slug,例如Myslug,如下所示:

class House extends Eloquent
{
use Sluggable;
public function sluggable()
{
return [
'slug' => [
'source' => 'myslug'
]
];
}
public function getMyslugAttribute() {
return 'house-with-' . $this->bedrooms.'-bedrooms;
}
}

或任何你想要的

然后将其存储在数据库中,并从您想要的任何位置从表中调用它,如下所示:

$house->slug;

您可以根据需要定义网址

<a href="{{ url('houses/'.$house->id.'/'.$house->slug)}}">house link</a>

最新更新