I have a table post and it have a column content. The content column is text. I want to get the most used words in content today with eloquent
Asked
Active
Viewed 1,251 times
2
-
What have you tried so far? – Jaime Rojas Oct 04 '18 at 20:02
-
is it laravel 5 or greater? – Fnr Oct 04 '18 at 20:32
-
possible duplicate of https://stackoverflow.com/questions/44894294/laravel-eloquent-get-most-common-value-in-a-database-column – Salman Zafar Oct 04 '18 at 20:34
-
Is the `content` column like the body of the `post` and you want to grab all the text in all the content columns and grab the most used out of all of them? – Das Oct 04 '18 at 20:51
2 Answers
2
Try this, assuming table name = post
and field name = content
:
$mostUsed = Post::take(1)
->groupBy('content')
->orderBy('content', 'desc')
->count('content');
Will get the first most common content
in the table, and:
$mostUsed = Post::groupBy('content')
->orderBy('content', 'desc')
->count('content');
Will get the registers ordered from the most common to the most rare. By the way, this is just an adaption from MySQL to Eloquent according to this example

Fnr
- 2,096
- 7
- 41
- 76
2
I think what you are looking for is this.
NOTE: since you have not provided any table structure, I don't know how to filter today's posts. I hope there is a column named date
.
Count all the words that has used today.
// array of all the content strings.
$contents = Post::where('date', date('Y-m-d'))->pluck('content');
// final result will be stored here as a key value pair.
// used count against each word.
$word_count = [];
foreach($contents as $content) {
// array of each word in the content separated by 'space'.
$words = explode(' ', $content);
foreach($words as $word) {
// if the word has already used +1 the count, else set the count as 1.
$count = array_key_exists($word, $word_count) ? ($word_count[$word] + 1) : 1;
// set new word count to the array.
array_set($word_count, $word, $count);
}
}
$most_used_word = array_search(max($word_count), $word_count);

Tharaka Dilshan
- 4,371
- 3
- 14
- 28