In Laravel
there is a feature that allows us to return a value, in a model property, as if it were in the table.
For example, if you have the conteudo
field in your table, you can have the magic conteudo_resumido
property returned from that original content.
We can do this by adding a method in the Model, which starts with get
, followed by the name with StudlyCase, and then with the word attribute
. That is:
MyModel :: getCountSaveAttribute ()
Example:
class Post extends \Eloquent
{
protected $appends = ['conteudo_resumido'];
public function getConteudoResumidoAttribute()
{
return str_limit($this->getAttribute('conteudo'), 200, '...');
}
}
From this, we can do the following in the call of our model Post
:
@foreach($posts as $post)
<li>{{ $post->conteudo_resumido }}
@endforeach
I have used the property appends
to determine that the magic method will be loaded along with the result of a common query, because if it needs it in json
, it will already be returned automatically.
Update
If you are experiencing problems with broken HTML tags because of the "truncate" generated by the str_limit
function, simply change the method described above by putting the strip_tags function before using str_limit
.
str_limit(strip_tags($this->getAttribute('conteudo')), 200);
This will only count the text characters, not those of the tag, and you will not have problems with broken HTML tags.