BLOG // May 6, 2021

Minutes to read Laravel 8 Helper

We've recently spoken about reading time in plain JavaScript, and we're doing doing Laravel. Using the Str::macro function you can add additional helpers to the Laravel Str class.

In this case we want to add a readingTime call that returns the number of minutes required to read a string of text.

The code

Str::macro('readingTime', function (...$text) {
    $totalWords = str_word_count(implode(' ', $text));

    $minutes = ceil($totalWords / 200);
    $minutes = max(1, $minutes);

    return ($minutes > 1) ? $minutes . ' minutes' : $minutes . ' minute';
});

You can add this macro function to a service provider boot() method in your application. For example, adding it to app/Providers/AppServiceProvider.php, it looks like the following:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Str::macro('readingTime', function (...$text) {
            $totalWords = str_word_count(implode(' ', $text));

            $minutes = ceil($totalWords / 200);
            $minutes = max(1, $minutes);

            return ($minutes > 1) ? $minutes . ' minutes' : $minutes . ' minute';
        });
    }
}

Using your Laravel Reading Time helper

You can then call your new readingTime helper function like so:

echo Str::readingTime($yourText);

Or in a blade file like so:

{{ \Illuminate\Support\Str::readingTime($yourText) }}

Tips

This code requires PHP 8, but it should be easy enough to downgrade to PHP7.3. It also depends on Laravel 8.

For any standard PHP implementation here is a simple function you can call instead:

function readingTime($text): string 
{
    $totalWords = str_word_count($text);

    $minutes = ceil($totalWords / 200);
    $minutes = max(1, $minutes);

    return ($minutes > 1) ? $minutes . ' minutes' : $minutes . ' minute';
}

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.