0
votes

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.

1
just change $post->author() to $post->author - Joseph
@Joseph I have just tried that and receive a null value. The users/authors of the blog posts do exist in the DB - Newb 4 You BB
please check the answer below - Joseph

1 Answers

2
votes

All the problem is laravel by default get the relation from the method name and you add custom names so to fix it you need to add the second argument for each relation like this

User Model

public function blogPosts() {
   return $this->hasMany(BlogPost::class, 'user_id');
}

BlogPost

public function author() {
    return $this->belongsTo(User::class, 'user_id');
}

At the end in your BlogPostResourceCollection you need to access the author data all you need is to write ->author not ->author()

for more info, you could check the One-To-Many relation here