Str::limit() or substr().Post::truncated() scopes).cache()->remember()) to mitigate DOM parsing overhead.excerpt fields).intl/mbstring.Truncator::truncate() requires no configuration.html5-php for malformed markup (if input quality is unreliable).intl/mbstring for accurate truncation of Unicode text.DOMDocument loads entire HTML into memory; risky for >1MB strings.html5-php, fails on non-standard HTML5 (e.g., <div><p>).<table> inside <div>).mbstring; test with scripts like Arabic, CJK, or emoji.<article><section>).html5-php justified?intl/mbstring.Str::limit() fallback)Blade::directive('truncate', function ($expression) {
return "<?php echo \\HtmlTruncator\\Truncator::truncate($expression[0], $expression[1], $expression[2] ?? '…'); ?>";
});
Usage: @truncate($post->content, 10).Truncator for dependency injection:
$this->app->singleton(Truncator::class, function () {
return new \HtmlTruncator\Truncator();
});
public function scopeTruncated($query, $words, $ellipsis = '…') {
return $query->selectRaw("
CONCAT(
SUBSTRING_INDEX(
HtmlTruncator\Truncator::truncate(content, $words, '$ellipsis'),
'…',
1
),
'…'
) as truncated_content
");
}
return response()->json([
'data' => [
'type' => 'article',
'attributes' => [
'title' => $post->title,
'excerpt' => Truncator::truncate($post->content, 5),
],
],
]);
excerpt(length: Int!)).$truncated = Truncator::truncate("<p>Test <strong>HTML</strong></p>", 3);
cache()->remember():
$truncated = cache()->remember("truncated_{$post->id}", now()->addHours(1), function () use ($post) {
return Truncator::truncate($post->content, 10);
});
truncated_excerpt column via migration:
Schema::table('posts', function (Blueprint $table) {
$table->text('truncated_excerpt')->nullable();
});
Post::created(function ($post) {
TruncatedExcerptJob::dispatch($post);
});
truncate() to support length_in_chars as a named param.ext-dom (enabled by default in Laravel).ext-intl/ext-mbstring: For i18n (enable in php.ini).masterminds/html5: For HTML5 parsing (composer require).| Step | Priority | Effort | Dependencies |
|---|---|---|---|
| 1. Install package | High | Low | Composer |
| 2. Unit tests | High | Medium | Edge-case HTML samples |
| 3. Blade directive | Medium | Low | Laravel Blade |
| 4. Caching layer | High | Medium | Laravel Cache |
| 5. API response helpers | Medium | Medium | JSON:API spec |
| 6. Database column (optional) | Low | High | Migration system |
| 7. Monitoring | Low | Medium | Laravel Logging/Sentry |
laravel branch for PHP 8How can I help you explore Laravel packages today?