问题
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