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!
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;
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,'...');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With