Pondikpa Tchabao
Pondikpa Tchabao

Reputation: 3665

Laravel: get the most used words with eloquent

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

Upvotes: 2

Views: 1408

Answers (2)

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

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);

Upvotes: 2

Fnr
Fnr

Reputation: 2274

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

Upvotes: 2

Related Questions