Articles Snippets Projects

Laravel text reading time macro

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