How to Truncate String in Laravel

Published on January 11, 2021 54 sec read

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *