0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Thomas Jensen
  • 2,138
  • 2
  • 25
  • 48
  • What's the problem? Aren't you already passing $article to your controller? Can't you just create that url in the controller and pass it using with('url', $url)? – Antonio Carlos Ribeiro Aug 29 '14 at 22:33
  • Forgot to mention: I am passing an array of articles to the view, I guess I can enumerate though them all and build of an array of URLs and pass that. Seems a little dirty, I was hoping there was some way I could do something like this with the framework. – Thomas Jensen Aug 29 '14 at 22:37

1 Answers1

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 }}
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • I added an accessor in my model, thank you sir! This is just what I was looking for:) The "view presenter" term is new to me, I'll have to read up on that. – Thomas Jensen Aug 29 '14 at 22:54
  • Starred! Thanks again, that looks very interesting. I definitely see that being useful in many situations :) – Thomas Jensen Aug 29 '14 at 22:58
  • Every time you need to do some kind of modification/formatation/calculation in the content you need to show in your view, you are supposed to do it in a presenter. :) – Antonio Carlos Ribeiro Aug 29 '14 at 23:00
  • I went for the presenter solution, much cleaner:) But shouldn't there be a `return` before the `URL::route`? I can't seem to get it working without it... – Thomas Jensen Aug 30 '14 at 10:44