I am having problems accessing an object retrieved from a nested relationship. I can only access the nested relation as an array (it is returned as json). The other relation is returned fine as a Model. (I'm totally new to Laravel 4 and a lot of its concepts btw).
So say I use, $category = Category::with('publications.author')->find(5);
I can iterate over the publications using $category->publications
and $category->publications[0]->title
will return what I expect.
The problem I have is when trying to access author
:
$category->publications[0]->author->last_name
throws an exception - 'Trying to get property of non-object'
but:
$category->publications[0]->author['last_name']
will return what I want.
This isn't a showstopper but I would like it to work as it looks like it should work according to the Laravel documentation.
So, where am I going wrong? Am I going about this the wrong way? Have I missed something? I have checked my method names and relations defined and it all looks correct to me.
These are my three Models: 'Category', 'Publication', 'Author'. Their relationships are defined as below:
Category
class Category extends \Eloquent {
protected $table = 'category';
public function publications()
{
return $this->hasMany('Publication');
}
public function authors()
{
return $this->hasManyThrough('Publication', 'Author');
}
}
Publication
class Publication extends \Eloquent {
protected $table = 'publication';
public function author()
{
return $this->belongsTo('Author');
}
public function category()
{
return $this->belongsTo('Category');
}
}
Author
class Author extends \Eloquent {
protected $table = 'author';
public function publications()
{
return $this->hasMany('Publication');
}
}
I want to use the following code to get the data I want:
$items = array();
$category = Category::with('publications.author')->find(5);
foreach($category->publications as $v)
{
$items[] = new ContentTeaser($v->title, $v->author->last_name, $v->slug, $v->default_image);
}
Thanks for taking a look.