2

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

Pondikpa Tchabao
  • 3,285
  • 6
  • 17
  • 24

2 Answers2

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