异常 属性 [ ] 在此集合实例上不存在

Exception Property [ ] does not exist on this collection instance

我正在尝试获取参加考试的学生的 ID。我在 Laravel 中使用关系,但我不知道我错过了什么。这是代码:

我的模型

考试模式:

class Examen extends Model
{
    protected $guarded = [];


    public function professor()
    {
        return $this->belongsTo(Professor::class,'prof_id');
    }

    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    public function examen_passers()
    {
        return $this->hasMany(Examen_passer::class);
    }
}

应试模式:

class Examen_passer extends Model
{
    protected $guarded = [];

    public function examen()
    {
        return $this->belongsTo(Examen::class);
    }

    public function reponses()
    {
        return $this->hasMany(Reponse::class);
    }

      public function reponsestxt()
    {
        return $this->hasMany(Reponsetxt::class);
    }
}

我的控制器:

public function corriger()
    {
 $examen = Examen::where('prof_id',Auth::guard('professor')->id())->get();
 dd($examen->examen_passers->etudiant_id);

}

使用 pluck() 从您的路人那里获取所有 ID collection:

$examen->examen_passers->pluck('etudiant_id');

此方法将从您的 collection 和 return 中的每个项目中获取 etudiant_id 的值,并将它们放在一个数组中。