Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Words not Characters in Laravel

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?

like image 782
daugaard47 Avatar asked Mar 05 '23 00:03

daugaard47


1 Answers

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
like image 85
Joe Avatar answered Mar 07 '23 16:03

Joe