Get random records from database in Laravel

If you want to get random records in Laravel, we have a function called orderByRaw which you can attach to the query you are building:

$posts = Post::orderByRaw("RAND()")->limit(5)
       ->pluck("title"); //get();
   
dd($posts);

Some examples:

Illuminate\Support\Collection {#1433 ?
 #items: array:5 [?
   0 => "Los Arrays en Programación - 18"
   1 => "Dismissible Widget en Flutter"
   2 => "Conectar una app en Flutter a la base de datos Cloud Firestore en Firebase"
   3 => "Ejecutar script automáticamente con Cron en Linux"
   4 => "Escalado y recortando imágenes con Canvas"
 ]
}
Illuminate\Support\Collection {#1433 ?
 #items: array:5 [?
   0 => "El elemento symbol para los SVG en HTML"
   1 => "Desarrollando aplicaciones de Realidad aumentada con Wikitude (parte 1)"
   2 => "Las propiedades flex-grow, flex-shrink y flex-basis"
   3 => "¿Qué es Blender 3D? y primeros pasos (tutoriales)"
   4 => "Problemas con Android Studio y sus proyectos"
 ]
}

Remember that the where that is inside the whereHas allows us to add DEFAULT validations in the relationship, that is, the category, in such a way that in this case, although both post and category have a column called id, by default it will look for the field (id in this case) in the category table (the relation) if it exists, it uses the one of the relation, and if it doesn't exist, it would use the one of post.
orderByRaw with relations

The most interesting thing is that you can attach it with whereHas to be able to filter by some relation; for example, a post has a category assigned to it, so:

$posts = Post::whereHas('category', function ($query) {
           $query->where('id', '<', '10');
       })->orderByRaw("RAND()")->limit(5)
       ->pluck("title"); //get();
   
dd($posts);

Some examples:

Illuminate\Support\Collection {#1432 ?
 #items: array:5 [?
   0 => "Creando un fondo vivo con CSS"
   1 => "4+1 selectores CSS esenciales al momento de programar"
   2 => "Creando un carrusel animado con CSS"
   3 => "Selectores en JavaScript"
   4 => "Múltiples capas: Efecto de apertura de una puerta con CSS"
 ]
}
Illuminate\Support\Collection {#1432 ?
 #items: array:5 [?
   0 => "Múltiples bordes en un contenedor con CSS"
   1 => "¿Cómo hacer un sistema de grid (rejillas) responsivo casero en CSS?"
   2 => "Plugin para las Cookies en JavaScript"
   3 => "¿Cómo obtener la resolución de pantalla con JavaScript/jQuery?"
   4 => "Formas geométricas con CSS (parte 2)"
 ]

Of course, with limit() you can limit or indicate how many records you want to get at most; this is to give you some ideas, but you can adapt other functions to it.

Otherwise, you can apply any number of additional conditions before using the orderByRaw method.

If you want more information about Laravel, remember that you have the Laravel course from scratch.

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.