Home > Back-end >  Laravel blog rating 2 migrations
Laravel blog rating 2 migrations

Time:12-04

i made a blog in laravel and now created a new migration for a rating system. i call it with

@foreach($blogs as $key => $blog)
    $blog->title....
    @foreach($ratings as $key => $rating)
        @if( $rating->blog_id == $blog->id)
        <br> rating found!
        <br> {{ $rating->rating_total }}
        <br> {{ $rating->rating_amount }}
        @endif
    @endforeach
@endforeach

it works but it doesnt seem right to run a for loop on every blog post in order to get the rating.

how can i solve this better?

thanks

CodePudding user response:

You could use one that show this. Like this: <input id="input-1" name="input-1" data-min="0" data-max="5" data-step="0.1" value="{{ $post->averageRating }}" data-size="xs" disabled="">

CodePudding user response:

Since you have the relationship setup from Blog to Rating you can eager load the 'rating' relationship for each Blog post:

$blogs = Blog::with('rating')->...->get();

Then in Blade when you are looping your $blogs you will have access to it's rating:

@foreach($blogs as $blog)
    {{ $blog->title }}
    @if($blog->rating)
        {{ $blog->rating->rating_total }}
        {{ $blog->rating->rating_amount }}
    @endif
@endforeach
  • Related