Calculating Article Reading Time Using Laravel Macro

Hello Artisan in this quick example i am going to show you aravel calculate reading time in laravel. You have seen that many blog share with us one thing that estimated reading time of the article which you are reading.

Now in this example i am going to share with you how you can do that using Laravel macro. When you want to extend some core classes’ functionality in Laravel, Macros are best option to do that.

So let's see that how we can calculate laravel read time:

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


Hope it can help you.


#laravel #laravel-8x #laravel-macro