Laravel iterate hasMany with count

Categorized as Laravel Tagged ,

Here’s how to loop through the collection with hasMany relationship.

Model:

class Platforms extends Model
{
    use HasFactory;

    public function courses()
    {

        return $this->hasMany(Post::class, 'platform_id');

    }
    
}

Controller:

class PlatformsController extends Controller {

  public function index()
  {
      $platforms = Platforms::with('courses')->get();
      return view('platforms.index')->with('platforms', $platforms);
  }

}

Blade view:

<div class="prose">

    @foreach ($platforms as $platform)    
        <p>{{ $platform->name }}</p>
        <ul>
          <li>{{ $platform->courses->count() }}</li>

          @foreach ($platform->courses as $course)

          <li>{{ $course->title }}</li>

          @endforeach

        </ul>
    @endforeach

  </div>

Leave a reply

Your email address will not be published. Required fields are marked *