php - How to get Laravel rows randomly, from filtered rows?

53

I've got a Laravel model, (Cars). I'd like to get 4 random cars, but only picking these 4 random cars from a subset of the top 10 cars, as ranked by their 'score_total'

I've tried the code below, but the inRandomOrder doesn't seem to have any effect. Any advice would be much appreciated. I'm on Laravel 5.4.

Cars::orderBy('score_total','DESC')->take(10)->inRandomOrder()->take(4)->get();
558

Answer

Solution:

Try to userandom instead :

$cars = Cars::orderBy('score_total','DESC')->take(10)->get();
$random =  $cars->random(4);

People are also looking for solutions to the problem: javascript - How to auto-save and auto-update textarea

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.