Estimated Reading Time Calculate in Laravel

Dec 27th 24 byAdmin inProblem Solving


Hi artisans, in this snippet, we are going to learn how to calculate estimated reading time in Laravel. We'll use Laravel Macro.

In Laravel, a macro is a way to extend the functionality of a class by adding custom methods to it at runtime. This means you can add new methods to a class without having to modify the class itself. Macros can be used on various Laravel classes such as Collection, Request, Response, etc.

Create Reading Time Macro

Open app\Providers\AppServiceProvider.php file and in the boot() method add this macro:

use Illuminate\Support\Str;

// macro: reading time
Str::macro('readingTime', function ($text) {
    $totalWords = str()->wordCount($text);
    $minutesToRead = round($totalWords / 200, 1);

    return (int)max(1, $minutesToRead) . ' min';
});

Here, we extended Laravel Str class and 200 (words per min) is the average reading speed.

The average reading time can vary depending on factors such as reading speed, complexity of the material, and familiarity with the subject matter. However, a rough estimate for the average reading time for an adult is around 200-300 words per minute.

Use the Marco

Now, we can easily use the readingTime() Macro like Laravel Str methods anywhere in our application.

$readingTime = str()->readingTime("This is an article!"); // 1 min read

That's all. Happy coding ❤️!

Leave a comment

3 comments

MH
Mahmud Hossain
July 16, 2026

Well written. Bookmarked this for my team's reference. Looking forward to more content like this.

SB
Sumaiya Begum
July 15, 2026

Does this approach also work for larger datasets? Our team is dealing with something similar at scale.

RK
Rafiq Khan
July 14, 2026

Really insightful article! This is one of the clearest explanations I've come across. The examples make it very easy to understand.

AD
AdminAdminJuly 14, 2026

Thank you Rafiq! Glad it was helpful.