所以,這裏是我落得這樣做:
routes.php
,創建自定義路線show
和edit
。剩下的部分使用的資源:
Route::pattern('id', '[0-9]+');
Route::get('articles/{id}/{slug?}', ['as' => 'articles.show', 'uses' => '[email protected]']);
Route::get('articles/edit/{id}', ['as' => 'articles.edit', 'uses' => '[email protected]']);
Route::resource('articles', 'ArticlesController', ['except' => ['show', 'edit']]);
控制器,增加了slug
輸入參數有一個默認值。重定向請求,如果塞缺失或不正確,因此,如果標題改變會重定向並返回一個HTTP 301(永久移動):
public function show($id, $slug = null)
{
$post = Article::findOrFail($id);
if ($slug != Str::slug($post->title))
return Redirect::route('articles.show', array('id' => $post->id, 'slug' => Str::slug($post->title)), 301);
return View::make('articles.show', [
'article' => Article::with('writer')->findOrFail($id)
]);
}
查看主持人,我本來在我的模型類的東西。但它移動到視圖類主持人這個答案的基礎上:https://stackoverflow.com/a/25577174/3903565,安裝和使用這樣的:https://github.com/laracasts/Presenter
public function url()
{
return URL::route('articles.show', array('id' => $this->id, 'slug' => Str::slug($this->title)));
}
public function stump()
{
return Str::limit($this->content, 500);
}
查看,得到的觀點主持人的網址:
@foreach($articles as $article)
<article>
<h3>{{ HTML::link($article->present()->url, $article->title) }} <small>by {{ $article->writer->name }}</small></h3>
<div class="body">
<p>{{ $article->present()->stump }}</p>
<p><a href="{{ $article->present()->url }}"><button type="button" class="btn btn-default btn-sm">Read more...</button></a></p>
</div>
</article>
@endforeach
的http:// stackoverflow.com/questions/21949298/how-to-add-slug-and-id-url-to-laravel-4-route – JofryHS 2014-08-29 12:35:52
我看過那篇文章,他說:「我的目標是繼續使用Numbers * *還可以使用Slugs **獲得更好的SEO網址「。我想用這兩個。 – 2014-08-29 12:37:51
它可能仍然非常接近該帖子的第一個答案。在這種情況下,如果沒有':: resource',你可能是最好的,因爲你需要爲你的slug指定額外的參數。就像':: controller('articles/{id}/{slug?}',ArticlesController');'可能會訣竅 – JofryHS 2014-08-29 12:40:40