Laravel iterate hasMany with count

Categorized as Laravel Tagged ,

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


class Platforms extends Model
    use HasFactory;

    public function courses()

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



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>
          <li>{{ $platform->courses->count() }}</li>

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

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




Leave a reply

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