我想在我的文章路由中同时使用ID和slug。所以我想要的不是/articles/ID
,而是/articles/ID/slug
。
实际上,我不需要slug变量;它只是为了使URL更具可读性和SEO,所以我将使用ID
作为检索文章的标识符。
如果输入了URL /articles/ID
,我想重定向到/articles/ID/slug
。/articles/ID/edit
必须有一个例外,因为它打开了编辑文章的表单。
我在谷歌上搜索过这个网站,但我只找到了用鼻涕虫代替ID的例子,而不包括两者。
我该如何做到这一点?我可以使用URL
类来获取文章的完整URL(/articles/ID/slug
)吗
当前路由配置:
Route::resource('articles', 'ArticlesController');
所以,我最终做的是:
routes.php
为show
和edit
创建了一个自定义路由。使用了其他资源:
Route::pattern('id', '[0-9]+');
Route::get('articles/{id}/{slug?}', ['as' => 'articles.show', 'uses' => 'ArticlesController@show']);
Route::get('articles/edit/{id}', ['as' => 'articles.edit', 'uses' => 'ArticlesController@edit']);
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);
}
查看,从视图演示器获取url:
@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