DEV Community

Hilmi Hidayat
Hilmi Hidayat

Posted on • Originally published at divisidev.com on

Estimated Reading Time using Laravel Macro

If you are building an information system that shares text-based content, you may need to add an estimated reading time for that content. Some time ago, Marcel Pociot shared a code snippet for the helper using macro in Laravel.

Here's a nice little string helper macro for @laravelphp , that gives you the estimated reading time for the given text(s).

200 is the (pessimistic) avg. reading amount of words that an adult reads per minute. pic.twitter.com/QKypiT5tnT

โ€” Marcel Pociot ๐Ÿงช (@marcelpociot) May 5, 2021

The estimated reading time can help the reader estimate how long the user can read the content to completion.

And here is the code snippet.

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

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

$est = Str::readDuration($post->body). ' min read';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)