Limiting Blade String Output in Laravel
You are working on a feature to display a preview of the next post title, but the default output is too long for your layout requirements. Your current Blade template looks like this:
<span class="blog-title-next">{{ $post->nextPost()['title'] }}</span>
The goal is simple: truncate the string so it only shows the first 10 characters. In PHP, there are several ways to achieve this, ranging from native language functions to Laravel-specific helpers. The best approach depends on whether you need a raw substring or a truncated sentence with proper word boundaries.
Using substr() in Blade
The most direct solution is to wrap your output in the native PHP substr() function. This function takes three arguments: the string, the starting position (0-indexed), and the length. You can pass the result of your array access directly into it.
Update your Blade view like this:
<span class="blog-title-next">
{{ substr($post->nextPost()['title'], 0, 10) }}...
</span>
This approach is lightweight and requires no external packages. It works perfectly if you are okay with cutting off the text arbitrarily at the character count. For example, a title like "How to build scalable APIs" becomes "How to build". While technically accurate, this can sometimes look awkward if it splits a word in the middle or leaves dangling punctuation.
Handling Word Boundaries
If your design requires a cleaner breakâwhere the text ends at a natural space rather than slicing through a wordâyou should use Str::limit() from Laravel's helpers. This method is part of the underlying Illuminate\Support\Str class and handles edge cases more gracefully.
You can call this directly in Blade using the global helper syntax:
<span class="blog-title-next">
{{ str_limit($post->nextPost()['title'], 10) }}...
</span>
Under the hood, str_limit() attempts to find the nearest word boundary before truncating. If the string is shorter than the limit, it returns the original string unchanged. This prevents issues where a long title might be displayed as an empty string if not handled correctly, though the default behavior usually just returns the full text if it's too short.
Performance Considerations
When dealing with large datasets or high-traffic sites, every byte counts. The substr() function operates on a string copy of the original data. While this is negligible for single-character views, Str::limit() might perform additional checks to find word boundaries.
However, in the context of displaying a few titles on a feed, these performance differences are imperceptible. The trade-off here is code clarity versus raw speed. substr() is explicit about its mechanics, while str_limit() offers semantic clarity by describing what you want (a limited string) rather than how you calculate it.
Security and Sanitization
It is important to remember that neither function performs sanitization. If the title contains user-generated content or unescaped variables within the title itself, Blade's default escaping ({{ }}) handles the HTML safety. However, if you were to use the @raw directive or single braces ({!! !!}) to bypass escaping for styling reasons, you must ensure the source data is safe before truncation. Always trust your input validation logic upstream; do not rely on character counting to fix SQL injection or XSS vulnerabilities.
Conclusion
For a quick fix that respects character counts exactly, substr() is your tool of choice. If you prefer readable output that avoids cutting words in half, str_limit() provides the necessary logic out of the box. Both methods integrate seamlessly into existing Laravel controllers and views without requiring changes to your backend logic.