Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
Make an order from avg() function

I'm currently working on one Laravel app and I would like to have this one section where top rated books are shown. I stored my ratings in Rating model. My idea was like this below, but, indeed, it didn't work. I would be really, really happy if someone answered me correctly.

$book = Book::all();
$ratings = Rating::where('book_id', '=', $book->id)->orderBy(avg('rating'));
return view('toprated')->withRatings($ratings);

toprated.blade.php

@foreach($ratings as $rating)
    {{ $rating }}
@endforeach
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can update your code like:

$ratings = Articles::where('state', '=', '1')
   ->select(array('ratings.*',
       DB::raw('AVG(rating) as ratings_average')
       ))
   ->orderBy('ratings_average', 'DESC')
   ->get();
over 4 years ago · Santiago Trujillo Denunciar

0

If you need to use a MYSQL function, use orderByRaw:

$ratings = Rating::where('book_id', '=', $book->id)->orderByRaw("avg(rating)");
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda