Derek
Derek

Reputation: 5037

Merge two eloquent collections in Laravel

I have a system that allows users to create projects and assign tasks. Now I am trying to scope a view to show all projects created by or assigned to the current user. I have many to many relationships set up with three tables users, projects and project_user. Where the projects table has a column user_id for who "owns" it.

I tried using the merge method for collections based on this question but I cant get it to work.

$projects = new \Illuminate\Database\Eloquent\Collection();

$userProjects = Project::where(array('company_id' => Auth::user()->company_id, 'user_id' => Auth::user()->id))
        ->orderBy('created_at', 'asc')
        ->get();


//foreach($userProjects as $up){
    $projects = $projects->merge($userProjects);
//}

$assignedProjects = User::where('id', Auth::user()->id)->with('project')->orderBy('created_at', 'asc')->get();

foreach($assignedProjects as $assigned){
    $projects = $projects->merge($assigned->project);
}
dd($projects->all());

Then I tried converting to arrays and then manually created an object but that didnt quite work either and Im worried about resources.

$userProjects = Project::where(array('company_id' => Auth::user()->company_id, 'user_id' => Auth::user()->id))
        ->orderBy('created_at', 'asc')
        ->get()->toArray();
$assignedProjects = User::where('id', Auth::user()->id)->with('project')->orderBy('created_at', 'asc')->get()->toArray();
$projects = array_merge((array) $userProjects, (array) $assignedProjects[0]['project']);
$cleaned = array_unique($projects, SORT_REGULAR);
$merge = array('projects' => (object) $cleaned);
$projects = (object) $merge;

dd($projects);

This is the user collection but I only need the project relations from this enter image description here

This is the project collection enter image description here

The goal is to somehow get these to collections combined so I can access it from a view using $project->title (for example).

It was working fine when I just did it for projects the user "owned", now how do I get it to work to show both projects owned by user and projects assigned to user?

Upvotes: 3

Views: 2915

Answers (1)

Razor
Razor

Reputation: 9855

You are looking for whereHas method:

$allUserProjects = Project::whereHas('users', function ($query) {
        // you can replace 'id' column by 'users.id' for clarity
        $query->where('id', Auth::user()->id); 
    })
    ->orWhere(function ($query) {
            $query->where('company_id', Auth::user()->company_id)
                  ->where('user_id', Auth::user()->id);
    })
    ->orderBy('created_at', 'asc')
    ->get();

Upvotes: 2

Related Questions