schutte
schutte

Reputation: 2166

How to get random row from the last 5 row?

EDITED: From the oldest 5 posts, I want to get one row from those in random.


How can I get a random row from the oldest 5 row?

I tried these below:

Post::oldest(5)->random()->first();

But return me an error:

Call to undefined method Illumi nate\Database\Eloquent\Builder::random()

Someone knows how to do it in simple and neatest way?

Upvotes: 2

Views: 207

Answers (2)

Benyou1324
Benyou1324

Reputation: 521

As @Tim Lewis said, don't use first but instead, you can write take + the number of items you want to display

return Post::inRandomOrder()->limit(5)->get()->take(1);
//or
return Post::oldest()->take(5)->get()->random();

The take method returns a new collection with the specified number of items: in this case, we took only one item, more info visit the docs Hope it helps

Upvotes: 1

Tim Lewis
Tim Lewis

Reputation: 29288

The Builder class doesn't have a random() method, but a Collection does. Also, oldest() doesn't take an integer as it's argument, it's looking for a column to use (uses created_at as a default).

Use the following query instead:

$posts = Post::inRandomOrder()->limit(5)->get();

Note: Don't use ->first() if you want multiple rows; ->first() returns the first row from the database, ->get() returns rows in a Collection.

Edit: Misread the question. See the query below:

$randomPost = Post::oldest()->limit(5)->get()->random();

Use the initial Post::oldest()->limit(5)->get() to get 5 Posts ordered by created_at, then use Collection logic to return a single entry via random().

Upvotes: 4

Related Questions