DEV Community

Cover image for Add Estimated reading time in Laravel
Hilmi Hidayat
Hilmi Hidayat

Posted on

Add Estimated reading time in Laravel

If you are building a news website or a website that publishes articles, you may need to add an estimated reading time on each page of the post. If you create a website with laravel, you can add an estimated reading time by using the helper macro in laravel as below.

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';
Enter fullscreen mode Exit fullscreen mode

don't forget to visit codelapan.com, and find articles on the topic of web development, web design, software testing and others.

Top comments (0)