Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Estimated reading time macro in Laravel

When you want to extend some of the classes’ functionality in Laravel, Macros are your best bet. Your imagination is the only limit to what you can do with macros.

For instance, I have recently come across a handly little macro shared by Marcel Pociot that gives you the estimated reading time for the given text(s).

Here’s how the macro looks like.

use Illuminate\Support\Str;

Str::macro('readDuration', function(...$text) {
    $totalWords = str_word_count(implode(" ", $text));
    $minutesToRead = round($totalWords / 200);

    return (int)max(1, $minutesToRead);
});

echo Str::readDuration($post->text). ' min read';

As you can tell, the macro essentially tries to calculate the average reading time, keeping in mind that an average human can read about 200 words per minute.

If the text comprises less than 200 words, it will return 1 minute.

Interestingly, as the macro callable spreads the $text, you can also pass multiple strings in the macro like so.

echo Str::readDuration($post->title, $post->text). ' min read';

Here’s the tweet by Marcel.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?