Estimated reading time macro in Laravel
When you want to extend some of the classes’ functionality in Laravel, Macros are your best bet. Your imagination is the only limit to what you can do with macros.
For instance, I have recently come across a handly little macro shared by Marcel Pociot that gives you the estimated reading time for the given text(s).
Here’s how the macro looks like.
use Illuminate\Support\Str;
Str::macro('readDuration', function(...$text) {
$totalWords = str_word_count(implode(" ", $text));
$minutesToRead = round($totalWords / 200);
return (int)max(1, $minutesToRead);
});
echo Str::readDuration($post->text). ' min read';
As you can tell, the macro essentially tries to calculate the average reading time, keeping in mind that an average human can read about 200 words per minute.
If the text comprises less than 200 words, it will return 1 minute.
Interestingly, as the macro callable spreads the $text
, you can also pass multiple strings in the macro like so.
echo Str::readDuration($post->title, $post->text). ' min read';
Here’s the tweet by Marcel.
Here's a nice little string helper macro for @laravelphp , that gives you the estimated reading time for the given text(s).
— Marcel Pociot 🧪 (@marcelpociot) May 5, 2021
200 is the (pessimistic) avg. reading amount of words that an adult reads per minute. pic.twitter.com/QKypiT5tnT
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.