Create an excerpt easy with Laravel

Ariel Mejia

June 11th, 2020 - 1 min read

In Laravel 7 this is a really easy feature by using the Str class from Illuminate\Support\Str namespace.

For a hypothetical Post model you can create a function like this:

use Illuminate\Support\Str;
class Post
{
    const EXCERPT_LENGTH = 100;
    protected $fillable = [
        ..., 'body'
    ]
    public function excerpt()
    {
        return Str::limit($this->body, Post::EXCERPT_LENGTH)
    }
}

So now in your blade files you can use this method:

<h1>{{ $post->title }}</h1>
<p>{{ $post->excerpt() }}</p>

Now it is easy to use it as a blade directive in appServiceProvider or any other provider

In any service provider:

/**
 * Bootstrap services.
 *
 * @return void
*/
public function boot()
{
    Blade::directive('excerpt', function ($text) {
        return "<?php echo Str::limit($text, 100); ?>";
    });
}

Usage in blade views:

<p>@excerpt($post->body)</p>

Another place to apply this feature is in JsonResource classes

Thanks for reading!


Ariel Mejia Illustration

Ariel Mejia

Laravel Senior Developer

Engineer with 7+ years of experience working in backend & frontend technologies
Open Source Maintainer of packages for Laravel community.

Stay up with Laravel

Sign up & get tips and tricks

You'll get monthly updates regarding my most recent articles and products.