Laravel Calculate Estimated Reading Time

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 ❤️!


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.