Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
코드
public function index()
{
$prj = Project::find(1);
$tasks = $prj->tasks();
return $tasks; // 여기서 발생
}
CODE
원인
에러 메시지
ErrorException in Response.php line 406:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
CODE
Relation 을 지정하고 관련된 데이타에 접근할 때 꼭 프로퍼티를 사용해야 하며 실수로 메소드 호출로 사용했을 경우 위와 같은 에러가 발생하며 HasMany 대신 HasManyThrough, MorphMany, belongsToMany 등 지정한 관계에 따라 다양한 클래스가 표시됨.
Eloquent 는 PHP 의 dynamic property 기능을 사용하여 relation table 을 가져오므로 꼭 프로퍼티로 접근해야 함.
조치
프로퍼티로 접근하도록 코드 수정
public function index()
{
$prj = Project::find(1);
$tasks = $prj->tasks; // property 접근
return $tasks;
}