Estimated Reading Time Calculate in Laravel
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.
Open app\Providers\AppServiceProvider.php file and in the boot() method add this macro:
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.
Now, we can easily use the readingTime() Macro like Laravel Str methods anywhere in our application.
That's all. Happy coding ❤️!
3 comments
Well written. Bookmarked this for my team's reference. Looking forward to more content like this.
Does this approach also work for larger datasets? Our team is dealing with something similar at scale.
Really insightful article! This is one of the clearest explanations I've come across. The examples make it very easy to understand.
Thank you Rafiq! Glad it was helpful.
