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
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();
If you need to use a MYSQL function, use orderByRaw:
$ratings = Rating::where('book_id', '=', $book->id)->orderByRaw("avg(rating)");