Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show blog post excerpt with Laravel

Tags:

php

laravel

I'm trying to show the excerpts from blog posts. I am able to do this with php and mysql. However, I am wondering if there is a more 'friendly' way of doing this within the Laravel framework.

Thanks!

like image 513
303K Avatar asked Nov 04 '13 11:11

303K


2 Answers

You can do it using the method words

Default is:

 words($value,$words = 100, $end='...');

You can implement it like this

Str::words($post->body);

Str::words($post->body,10); //will show first 10 words

Incase of any error like Str class not found use the following statement

use Illuminate\Support\Str;
like image 133
Aatish Sai Avatar answered Sep 28 '22 15:09

Aatish Sai


Sorry I am very late but hope that it will help someone:

Using it like this may throw "Class 'Str' not found error":

Str::words($post->body,10);

Use along with complete namespace, like this:

\Illuminate\Support\Str::words($post->body, 10);

OR with dots:

\Illuminate\Support\Str::words($post->body, 10,'...');

OR register the function as Facade in config/app.php, try adding it like this way:

'aliases' => [
...
        'Str' => Illuminate\Support\Str::class,
...
]

And then use Str:: any where!, and hence you are free you use: Str::words($post->body,10);

Need short and neat solution, just use Laravel's str_limit() helper function:

str_limit($post->body, 10);

OR

str_limit($post->body, 10,'...');
like image 25
Muhammad Sheraz Avatar answered Sep 28 '22 17:09

Muhammad Sheraz