Reputation: 123
I have got a NewsItem
Model with a property content
of a text
type. It's long.
Now, I want to return the whole content
in the show
action, but in the index
action I want to return only the first eg. 100 chars of the content
field.
I know I can use an accessor but I guess it will affect the show
action, too.
Thanks for help.
Upvotes: 1
Views: 142
Reputation: 698
I think an accessor would be the best solution. Someone may have a better one though.
Create a separate accessor called something like 'excerpt', use that one in index
and use 'content' in show
public function getExcerptAttribute()
{
return str_limit($this->attributes['content'], 100, '...');
}
Upvotes: 2
Reputation: 2614
Just modify the value before returning in the index method. This should work, unless you have a mutator for the content
attribute, that will interfere with this somehow:
$item->content = substr($item->content, 0, 100);
return $item;
This is fine for a single use case. If you find you need to do it in other locations, then you should add a method to your model which handles this for you, or even possibly a new model, which extends the NewsItem model, and has a set or get mutator for the content attribute.
Upvotes: 1