A String Helper For Estimating Read Time
Enhancing User Experience with a Custom Reading Time Estimator in Laravel
March 28, 2023
1k ViewsIn the fast-paced digital world, providing users with an estimated reading time can improve their experience by helping them manage their time efficiently. This feature has become increasingly popular on blog platforms and news websites. In this article, we will demonstrate how to create a custom method using Laravel's String class to estimate the reading time of a given text.
Creating a Reading Time Estimator:
To create a reading time estimator in Laravel, we will be using the Str
class provided by the Illuminate\Support
namespace. In the AppServiceProvider
, we will register our custom method using the Str::macro()
function, which allows us to extend the Str
class with additional functionality.
Here's the code to implement the reading time estimator in the AppServiceProvider
:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
Str::macro('readTime', static function (string $string): int {
return ceil(str_word_count(Str::squish($string)) / 200);
});
}
}
In the above code, we define a new method called readTime
using the Str::macro()
function. The method takes a string as input and calculates the reading time based on an average reading speed of 200 words per minute. We use the Str::squish()
method to remove any extra whitespace before counting the words.
Usage:
After implementing the reading time estimator, you can use it throughout your Laravel application like this:
use Illuminate\Support\Str;
$readingTime = Str::readTime($text);
echo "Estimated reading time: $readingTime minutes";
This method makes it easy to estimate the reading time of any text in your application, enhancing the user experience by providing valuable information to help them manage their time.
Conclusion:
In this article, we've demonstrated how to create a custom reading time estimator in Laravel using the Str
class and AppServiceProvider
. This method allows you to easily estimate the reading time of any text in your application, improving the user experience by providing a helpful time management tool. By leveraging Laravel's extensibility, you can add many more custom methods to suit your application's needs.
Bonus
See how to use this same process to effortlessly convert words to possessive form.
A String Helper for Apostrophes
Subscribe to unlock the test suite accompanying this article and ALL our exclusive content.