0

I have this kind of eloquent query where I need to take random rows from a table, with a limit, but it returns wrong, when I use limit, then it pulls only one row, no matter what number I take in as a limit. And when I don't use limit it returns random number of rows. Don't know what I am missing. This is the code.

$questions = $query->whereRaw('RAND()')->take($limit)->get();

Thanks in advance!

2
  • What is $limit set at? Commented Mar 11, 2016 at 13:39
  • I am taking limit from request, so it is not set to anything, but when I send a request with a limit of 10 I get only one row Commented Mar 11, 2016 at 14:19

2 Answers 2

5

You should have been using orderByRaw.

But there is a better solution, you can add this macro:

use Illuminate\Database\Query\Builder;

Builder::macro('orderByRandom', function () {

    $randomFunctions = [
        'mysql'  => 'RAND()',
        'pgsql'  => 'RANDOM()',
        'sqlite' => 'RANDOM()',
        'sqlsrv' => 'NEWID()',
    ];

    $driver = $this->getConnection()->getDriverName();

    return $this->orderByRaw($randomFunctions[$driver]);
});

So you can do: $query->orderByRandom()->take($limit)->get();

Sign up to request clarification or add additional context in comments.

4 Comments

I still only get one row, whenever I have some value in limit.
There is probably something else wrong in your code. Is $limit properly set? Does it work if you manually execute the query? Where does $query come from, what is applied to it previously?
Yes, something is obviously wrong with $limit, because when I set it manually, it executes correctly, I am taking $limit from request, and then apply it in the query
Ah, stupid mistake, I was sending request as an array, and then $limit was null, so that's why it didn't work, thank you for your help!
0

You are using RAND in your where, it shout be in the ORDER BY

$questions = $query->orderByRaw('RAND()')->take($limit)->get();

1 Comment

this is still returning the same

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.