Merging of two eloquent collections at Laravel

I have a system that allows users to create projects and assign tasks. I am now trying to cover the view to show all projects created or assigned to the current user. I have many different relationships configured with 3 tables users

, projects

and project_user

. If the projects table has a column user_id

for those who "own" it.

I've tried using the merge method for collections based on this question , but I can't seem to 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 the object, but that didn't 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 a collection of users, but I only want the project relationships from this enter image description here

This is a collection of projects enter image description here

The goal is to somehow collect them into collections so that I can access it from the view using $ project-> title (for example).

It worked fine when I was just doing this for projects that the user "owned", now how do I get it to work to show projects owned by the user and projects assigned to the user?

+3


source to share


1 answer


Are you looking for a way whereHas

:



$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();

      

+1


source







All Articles