In the Laravel
there is a resource that allows us to return a value, in a model property, as if it were in the table.
For example, if you have the field conteudo
in your table, you will be able to make the magic property conteudo_resumido
is returned from that original content.
We can do this by adding a method in Model, which starts with get
, followed by the name with Studlycase, and then with the word attribute
. That is to say:
MeuModel::getConteudoResumidoAttribute()
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 used the property appends
to determine that the magic method will be loaded along with the result brought from a common query, as in case you need it in the json
, it will already be automatically returned.
Updating
If you are facing problems with broken HTML tags because of the "truncate" generated by the function str_limit
, just change the method described above by placing the function strip_tags before the use of str_limit
.
str_limit(strip_tags($this->getAttribute('conteudo')), 200);
Thus, only text characters, not tag characters, will be counted, and you will not have problems with broken HTML tags.
Inserting that kind of logic into the view is not a good idea. If I need this same summary in another view of the application I need to duplicate this huge logic?
– gmsantos
yes indeed, but if I have to do this in the controller I will have to overwrite that array position, coreto?
– Fábio Jânio
See the @Wallace response. It’s already explaining very well how to solve this type of problem
– gmsantos
If the tags were the problem, just say the words, I edited the questions. And why use preg_replace if there are already strip_tags?
– Wallace Maxters
Just one more thing, from the database is returned an array with the content, in your example I think you are reading only a string. To make the summary of everything I have to use a right loop? Or the Standard provides some resource for this?
– Fábio Jânio
I did not understand very well. How so the bank returns a
array
?– Wallace Maxters