Laravel:将带有ID和slug的自定义URL传递到视图


Laravel: Passing custom URLs with both ID and slug to the view

我的文章URL包含ID和slug,格式为:/articles/ID/slug。只有ID用于记录查找,段塞只是用于SEO,不存储在数据库中。

目前,我在我的视图中(在foreach循环中)这样做:

$url = URL::route('articles.show', array('id' => $article->id, 'slug' => Str::slug($article->title)));

生成完整的URL,例如:articles/1/accusamus-quos-et-facilis-quia,但是我不想在视图中这样做。我想在控制器中执行此操作,并将其传递到视图,但我不知道如何执行。

编辑:我将多篇文章的数组从控制器传递到视图,所有文章都有唯一的URL,这取决于它们各自的ID和slug。

这样做的最好方法是使用视图演示器:

{{ $article->present()->url() }}

在您的演示者中:

public function url()
{
    URL::route('articles.show', array('id' => $this->id, 'slug' => Str::slug($this->title)));
}

但你可以在你的模型中创建一个acessor:

public function getUrlAttribute() 
{
    URL::route('articles.show', array('id' => $this->id, 'slug' => Str::slug($this->title)));
}

并用作:

{{ $article->url }}