Display summary content in Laravel 5.1

3

I have a controller that performs a paged query:

$noticias = Noticias::orderBy('created_at', 'desc')->paginate(4);

However, one of the columns returned is content . The column in question has a lot of text, how do you do it in Laravel so that it returns only a summary containing the first 380 characters or the first 200 words?

    
asked by anonymous 09.03.2016 / 19:23

2 answers

4

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.

    
10.03.2016 / 16:52
-1

I did it like this:

{{ preg_replace('/(<.*?>)|(&.*?;)/', '', \Illuminate\Support\Str::words($noticia->conteudo, 70, "...")) }}

With this I remove the html tags and special formatting, as well as limiting to a total of 70 words before inserting the three points, elements that represent the continuity of the content.

    
20.03.2016 / 04:42