I'm using Laravel 5.7 and was wondering what the correct way would be to limit the number of words, not characters, in a description I'm pulling from the database and outputting to a Blade/view.
I currently have this working by adding the following in my Blade file (notice the class Str is in the Blade/view):
@php use Illuminate\Support\Str; @endphp
{!! (nl2br(e(Str::words($test->testimonial, '25')))) !!}
The above limits my paragraph to 25 words, but I realize I should probably be using the Str class in my Controller, not Blade.
When I add use Illuminate\Support\Str;
in my controller and not the Blade I get the error that Str is missing.
Controller
use App\Testimonial;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
...
public function index()
{
$testimonial = Testimonial::all();
return view('testimonials.index',compact('testimonial'));
}
How can I use the Str class in the controller instead of the Blade?
Check Accessor and Mutator
class Testimonial extends Model
{
public function getTestimonialExcerptAttribute()
{
return Str::words($this->testimonial, '25');
}
}
and then you can use it on your blade templates or controllers..
@foreach($testimonials as $testimonial)
{{ $testimonial->testimonial_excerpt }}
@endforeach
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