How to Truncate String in Laravel

In this short article, I’m going to share how to truncate string in Laravel. Laravel 7 offers a more object-oriented, fluent string manipulation library built on top of Illuminate\Support\Str functions. Let’s see a few examples:

Table of Contents

  1. Truncate in Controller
  2. Truncate in Blade

Truncate in Controller

Using limit function, we can remove characters from string:

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog.')->limit(20);
dd($truncated); // The quick brown fox...

We can replace with any custom character. Let’s replace ... with >>>

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog.')->limit(20, ' >>>');
dd($truncated); // The quick brown fox >>>

We can also truncate words with words method:

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog.')->words(4);
dd($truncated); // The quick brown fox...

Truncate in Blade

Remove characters from string in blade:

{!! Str::limit('The quick brown fox jumps over the lazy dog.', 20) !!}

<!--The quick brown fox...-->

Truncate words in blade:

{!! Str::words('The quick brown fox jumps over the lazy dog.', 4) !!}

<!--The quick brown fox...-->

If we want, we can set namespace too:

{!! \Illuminate\Support\Str::words('The quick brown fox jumps over the lazy dog.', 4)  !!}

<!--The quick brown fox...-->

That’s all, artisans. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.