Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!