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

醉酒当歌 提交于 2020-01-06 05:43:12

问题


My articles URL contains both ID and slug, in this format: /articles/ID/slug. Only ID is used for record lookup, the slug is just there for SEO and is not stored in the database.

At the moment I am doing this in my view (inside a foreach loop):

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

To generate the complete URL, e.g: articles/1/accusamus-quos-et-facilis-quia, but; I do not want to do this in the view. I want to do it in the controller and pass it to the view, but I can't figure out how.

Edit: I am passing an array of multiple articles from the controller to the view, and all of them have unique URLs depending on their respective ID and slug.


回答1:


The best way of doing something like this is to use a view presenter:

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

And in your presenter:

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

But you can create an acessor in your model:

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

And use as:

{{ $article->url }}


来源:https://stackoverflow.com/questions/25577046/laravel-passing-custom-urls-with-both-id-and-slug-to-the-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!