Estimated Reading Time using Laravel Macro

EN • 3 years ago • 1 min read • 3483 views
Estimated Reading Time using Laravel Macro

Estimated Reading Time using Laravel Macro

en1 min read • 3483 views

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.

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';

Published on April 08, 2022
Last updated on June 18, 2025

If you like this post and want to support us, you can support us via buymeacoffee or trakteer.