显示来自3个表Laravel的数据

I am trying display data from 3 tables like this ->

course name | test name | question count


course name1 | test name1 | 3

I have relation between Test and Question 1:N

Test.php

public $table = 'Test';

protected $fillable = [
    'name',
];

public function question()
{
    return $this->hasMany('App\Question');
}

Question.php

public $table = 'Question';

public function test()
{
   return $this->belongsTo('App\Test');
}

TestController.php

public function courses(Subject $subject) {
    $subject_with_courses = Subject::with(['course'])->where('id', 

    $subject['id'])->first();

    $courses = Course::with(['test'])->get();
    $questions = $courses->question;

    return view('admin.test.list_course', [
        'courses' => $courses,
        'questions' => $questions,
        'subject' => $subject
    ]);
}

list_course.php

@foreach($courses as $course)
    <tr>
        <td>
            {{ $course->name }}
        </td>
        <td>
            @foreach($course->test as $test)
                {{ $test->name }}
            @endforeach
        </td>
        <td>
            @foreach($course->questions as $test)
                {{ $test->count() }}
            @endforeach
        </td>
    </tr>
@endforeach

I get error "Property [question] does not exist on this collection instance."

Can anybody help me with this, please ? Thank you!!

This is what is giving you the error:

TestController.php:

$courses = Course::with(['test'])->get();
$questions = $courses->question; // <---- $courses is a Collection not a Model

You are trying to access the questions property of the Model, but $courses is a Collection of Models.

You are trying to access Course model property but $courses is collection of Course

You can eager load the questions in your controller:

$courses = Course::with(['test', 'test.question'])->get();

The questions belong to the test and not the Course, so you cant call $course->question on the Course Model.

In your View:

@foreach($courses as $course)
    <tr>
        <td>
            {{ $course->name }}
        </td>

        <td>
            @foreach($course->test as $test)
                {{ $test->name }}
            @endforeach
        </td>

        <td>
            @foreach($course->test as $test)
                {{ $test->question->count() }}
            @endforeach
        </td>
    </tr>
@endforeach