Estimated reading time macro in Laravel

Amit Merchant · May 5, 2021 ·

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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?