skip to Main Content

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


  1. If you load the relationships then you shouldn’t really have to do much.

    Assuming you have a route like this:

    Route::get('/projects/{project}', [ProjectController::class, 'show'])->name('projects.show');
    

    Your controller can simply return the model with its relationships.

    public function show(Project $project)
    {
        $project->load(['members', 'invites']);
    
        return $project;
    }
    

    or if you’re returning data do a view

    return view('projects.show', ['project' => $project]);
    
    {{ $project->id }}
    {{ $project->... }}
    @foreach ($project->members as $member)
      {{ $member->id }}
      {{ $member->... }}
    @endforeach
    @foreach ($project->invites as $invite)
      {{ $invite->id }}
      {{ $invite->... }}
    @endforeach
    
    Login or Signup to reply.
  2. return AppModelsProject->with([
        'members', 
        'invites'
    ])->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search