Home > other >  Undefined variable: sub inside the foreach loop in laravel
Undefined variable: sub inside the foreach loop in laravel

Time:09-10

Controller:

public function dashboard()
{
    $course = Course::all();
    return view('content.dashboard',compact('course'));
}

View:

@foreach($course as $year)

    $sub = \App\Models\SubCourse::where('course_id',$year->id)->first();
    @dd($sub->id);

@endforeach

In the above code I am trying to get value of SubCourse but it throw an error i.e. Undefined variable: sub (View: C:\xampp\htdocs\example\resources\views\content\dashboard.blade.php). I don't know why? Please help me.

Thank you

CodePudding user response:

You Can Accessing Model Like this in PHP Tag

@foreach($course as $year)
   <?php
     $sub = \App\Models\SubCourse::where('course_id',$year->id)->first();
     @dd($sub->id);
    ?>
@endforeach
  • Related