Skip to content

Instantly share code, notes, and snippets.

@MohcinBN
Last active November 13, 2022 14:17
Show Gist options
  • Save MohcinBN/799d99ff9f5001aeb78dc0adf3c89b6b to your computer and use it in GitHub Desktop.
Save MohcinBN/799d99ff9f5001aeb78dc0adf3c89b6b to your computer and use it in GitHub Desktop.
Laravel 9 reading time for yuour posts
// add this function to your post model;
// reading time
//The average reader reads about 200 words per minute, so I decided to have less to make estimates more accurate
public function postReadingTimeEstimation($averageReadsPerMunite = 180)
{
$textOfTheBody = $this->body;
$totalWords = str_word_count(strip_tags($textOfTheBody));
$minutes = floor($totalWords / $averageReadsPerMunite);
$seconds = floor($totalWords % $averageReadsPerMunite / ($averageReadsPerMunite / 60));
if ($minutes < 60) {
$minutes = 1 . ' minutes';
}
return $minutes;
}
// call the function into your view
{{ $post->postReadingTimeEstimation() }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment