Laravel如何访问数组内对象?集合实例属性不存在报错排查
Hey there! Let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Looking at your actual data, $classroom->courses isn't a single Course object—it's a collection (array-like structure) of Course objects. When you try to access $classroom->courses->id, you're asking a group of courses for an id property, which doesn't exist on the collection itself. Same goes for $classroom->courses->coursteachers->id—coursteachers is also a collection, not a single teacher object.
Also, a quick note: in your original code, you wrapped the teacher properties in single quotes (like '$classroom->courses->coursteachers->id'), which would output the literal string instead of the variable's value. We'll fix that too.
Solution 1: For Single Course & Single Teacher (Matching Your Current Data)
Since your sample data shows one course with one teacher, you can use first() to pull the single item from each collection:
protected function formatted($classroom) { // Grab the first (and only) course from the collection $course = $classroom->courses->first(); // Grab the first (and only) teacher from the course's coursteachers collection $courseTeacher = $course->coursteachers->first(); return [ 'courses' => [ 'id' => $course->id, 'name' => $course->name, 'slug' => $course->slug, 'coursteachers' => [ 'id' => $courseTeacher->id, 'email' => $courseTeacher->email, 'uid' => $courseTeacher->uid, ] ], ]; }
Solution 2: For Multiple Courses & Teachers (Scalable Version)
If your classroom might ever have multiple courses or multiple teachers per course, use map() to iterate through each collection and format the data properly:
protected function formatted($classroom) { return [ 'courses' => $classroom->courses->map(function($course) { // Format all teachers for this course $formattedTeachers = $course->coursteachers->map(function($teacher) { return [ 'id' => $teacher->id, 'email' => $teacher->email, 'uid' => $teacher->uid, ]; }); // Format the course data return [ 'id' => $course->id, 'name' => $course->name, 'slug' => $course->slug, 'coursteachers' => $formattedTeachers ]; }) ]; }
This version will return an array of courses, each with their own array of teachers—perfect if your data grows to include multiple entries.
内容的提问来源于stack exchange,提问作者livreson ltc

