Truncate string in Laravel blade templates
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Is there a native truncate modifier for the Laravel blade templates like Smarty has? While PHP is indeed considered a templating engine, we understand your desire to use cleaner syntax within your Laravel views. In this blog post, we'll discuss alternative methods and approaches for handling string truncation in Laravel blade templates.
Alternative Approaches with Built-In Functions
The Laravel framework offers a set of built-in functions that you can use to implement your own truncate methods. First, let's see how we can achieve a similar result using the PHP native `substr()` function. Here's an example code:php
{{ str_replace(trim($text), substr($text, 0, 10) . '...', $text ) }}php
return [
// ...
'helpers' => [
'truncateText' => function ($text, $length = 10) {
return str_replace(trim($text), substr($text, 0, $length) . '...', $text);
},
],
];php
{{ truncateText($myVariable, 10) }}php
return [
// ...
'helpers' => [
'truncateText' => function ($text, $length = 10) {
$charactersPerWordAverage = 5; // adjust the value to your needs
$wordsInText = strlen($text) / $charactersPerWordAverage;
$maxTruncatedWords = floor($wordsInText * ($length / 10));
return str_replace(trim($text), substr($text, 0, max(strlen(substr($text, 0, $maxTruncatedWords)), 10)) . '...', $text);
},
],
];Using Custom Blade Components
Another option is to create your own blade component with a truncate function. Create a new directory named `Truncate` in your view's root, and place the following code inside a file named `truncate.blade.php`:php
{{-- /resources/views/components/truncate.blade.php --}}
@component('truncate', ['text' => $text])
@slot('text') {{$text}} @endslot
@slot('truncatedText') {{$truncatedText}} @endslot
@endcomponentphp
{{-- /resources/views/yourview.blade.php --}}
@component('truncate', ['text' => $longString])
@slot('text') {{$text}} @endslot
@slot('truncatedText') {{$truncatedText}} @endslot
@endcomponent