Im trying to return results for 2 models into one resource and finding it a bit difficult to understand.
I have a ‘project’, this project can have multiple ‘members’ and it can also have people that have been ‘invited’ … I want to return a list of all members associated with the project and also all people that currently have pending invites in the invite table.
My ‘project’ table has the following relationship
public function members(): HasMany
{
return $this->hasMany(Member::class);
}
and it also has another relationship;
public function invites(): HasMany
{
return $this->hasMany(Invite::class);
}
In my controller i have
$data = [
'members' => $project->members()->get(),
'invites' => $project->invites()->get()
];
But i am having trouble figuring out how to return this in a resource .. Or even if this is the best way to return the data, is there a better way using Eloquent?
Any help would be greatly appreciated
2
Answers
If you load the relationships then you shouldn’t really have to do much.
Assuming you have a route like this:
Your controller can simply return the model with its relationships.
or if you’re returning data do a view