Laravel 8
I have a couple models using eloquent relationships.
A User which can have many blog posts
public function blogPosts() {
return $this->hasMany(BlogPost::class);
}
And a BlogPost which belongs to the author
public function author() {
return $this->belongsTo(User::class);
}
My issue is that when I attempt to use one of these relationships, I am returned an empty object.
We can focus on the belongsTo() relationship.
I am attempting to use this relationship here:
class BlogPostResourceCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return $this->collection->map(function($post) {
return [
'id' => $post->id,
'author' => $post->author(),
'title' => $post->title,
];
});
}
}
Why am I getting an empty object for author?
Edit: the blog post table does have a foreign key user id column.
$post->author()to$post->author- Josephnullvalue. The users/authors of the blog posts do exist in the DB - Newb 4 You BB