Limit Words not Characters in Laravel
Asked Answered
B

1

6

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?

Buttonball answered 25/11, 2018 at 23:1 Comment(1)
U
13

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
Use answered 26/11, 2018 at 2:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.