2014-08-29 50 views
9

我想在我的文章路線中使用ID和slu both。所以,而不是/articles/ID我想要/articles/ID/slug如何在Laravel 4路由URL中使用ID和slug? (資源/ ID/slu 012)

我實際上並不需要slug變量;它只是在那裏使URL更具可讀性和搜索引擎優化,所以我將使用ID作爲檢索文章的標識符。

如果輸入的URL是/articles/ID,我想重定向到/articles/ID/slug/articles/ID/edit必須有例外,因爲這將打開編輯文章的窗體。

我已經搜索了一下,看了這個網站,但我只找到替換ID與slu examples的例子,不包括兩個。

我怎樣才能做到這一點?我可以使用URL類來獲取文章的完整URL(/articles/ID/slug)嗎?

當前路線配置:

Route::resource('articles', 'ArticlesController'); 
+0

的http:// stackoverflow.com/questions/21949298/how-to-add-slug-and-id-url-to-laravel-4-route – JofryHS 2014-08-29 12:35:52

+0

我看過那篇文章,他說:「我的目標是繼續使用Numbers * *還可以使用Slugs **獲得更好的SEO網址「。我想用這兩個。 – 2014-08-29 12:37:51

+1

它可能仍然非常接近該帖子的第一個答案。在這種情況下,如果沒有':: resource',你可能是最好的,因爲你需要爲你的slug指定額外的參數。就像':: controller('articles/{id}/{slug?}',ArticlesController');'可能會訣竅 – JofryHS 2014-08-29 12:40:40

回答

9

所以,這裏是我落得這樣做:

routes.php,創建自定義路線showedit。剩下的部分使用的資源:

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