dzuritaa's avatar

Obtaining random items of database

Hello there! I'm trying to obtain random items of a table in my database, but I'm not sure how.

Right now I'm using this eloquent code

Noticias::whereRaw('url_foto != " " AND id_tipos_noticias = "1"')->latest('created_at')->limit('8')->get()

But instead of the last 8 items I need 8 random items. Hope there is a way.

0 likes
8 replies
bestmomo's avatar
Level 52

@dzuritaa

Noticias::where('url_foto', '!=',  ' ')
->where('id_tipos_noticias', 1)
->orderByRaw("RAND()")
->take(8)
->get()

There is also the random method on Collection but I think less performant.

1 like
RachidLaasri's avatar

"order by rand()" is bad, i recommend generating a random number that exist in your database and select where the id equals to that random number. Use the lists method on eloquent to get all the IDs available on your table.

RachidLaasri's avatar

That says a subquery which is fine and you can read that on the URL i posted too, but does the author of this thread have a subquery?

dmytro23's avatar

привіт! код потрібно вдосконалити але можливо комусь підійде $count = self::count(); $randArr = []; $c=count($randArr);

    for($i=0;$i<5;++$i){
        $random_int = rand(1, $count);
        $arr = self::find($random_int);
        $key = in_array($arr, $randArr);

        if(!$key){
            array_push($randArr, $arr);
        }
    };
    
    return $randArr;

Please or to participate in this conversation.