如何使用雄辩的sluggable包在Laravel5.3中的url末尾追加一个slug?
我有一个能言善辩的软件包。我想创建如下url: 让我解释一下网址: houses和id表示rest架构所述的资源和id 有两间卧室的房子本身就是鼻涕虫。 动态部分是数字2,表示房子拥有的卧室数量。 所以我可以如何使用雄辩的sluggable包在Laravel5.3中的url末尾追加一个slug?,laravel,http,nginx,slug,Laravel,Http,Nginx,Slug,我有一个能言善辩的软件包。我想创建如下url: 让我解释一下网址: houses和id表示rest架构所述的资源和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
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网站上的教程,但无法让它工作,也不明白我在做什么
到目前为止,我有:
我的房子模型有一个弹头场
我定义了Sluggable特性:
我的模型:
use Cviebrock\EloquentSluggable\Sluggable;
class House extends Model
{
use Sluggable;
public function announcement()
{
return $this->belongsTo(\App\Announcement::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').
在模型中创建一个要显示为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;
或者你想要的任何东西
然后将其存储在数据库中,并从表中的任意位置调用它,如下所示:
class House extends Eloquent
{
use Sluggable;
public function sluggable()
{
return [
'slug' => [
'source' => 'myslug'
]
];
}
public function getMyslugAttribute() {
return 'house-with-' . $this->bedrooms.'-bedrooms;
}
}
$house->slug;
您可以根据需要定义url
<a href="{{ url('houses/'.$house->id.'/'.$house->slug)}}">house link</a>
您可以简单地实现这一点 途中
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>
将您的路线发布到我将用路线更新我的问题。我的路线没有什么特别之处,只是路线::资源('houses',HousesController')。我原以为需要定义一条路径来支持slug,但教程没有教我。