Reputation: 18283
When retrieving models from database and sending them to the client I want to include for each model the url to that resource.
Let's take as example this Article
model, with:
Storing the url to an article in the DB doesn't make sense, because it can be easily made up from id and title:
ex: http://www.example.com/articles/article_id/article_title
So, this is what I am doing now:
I use the $appends
array:
/**
* Additional attributes
*
* @var array
*/
protected $appends = array('article_url');
and created a getter for article_url
:
/**
* Get the article url attribute
*
* @return string
*/
protected function getArticleUrlAttribute()
{
return $this->exists
? url('articles', $parameters = array(
$this->getKey(),
Str::title(Str::limit($this->title, 100))
))
: null;
}
This works just fine. The problem is, that probably the model should not include any logic for creating urls. What is a good approach for this problem? Where should I create the url to the article before sending it to the client?
Upvotes: 1
Views: 707
Reputation: 311526
That sort of logic would usually go in whatever your framework's routing engine is. For instance, since it sounds like you're using Laravel, you'd probably make a Named Route -- call it, say, "canonical_article".
Then you can use the link_to_route
helper to have your framework generate the URL.
Upvotes: 1