Skip to content
Advertisement

Laravel get union between two objects

I have the following to get all organizations the logged in user owns

$user_owned_orgs = Organization::where('user_id', Auth::user()->id)->get();

and to get all organizations the logged in user is member of

$user_orgs = Organization::whereIn('id', function($query){
    $query->select('organization_id')
    ->from(with(new OrganizationUser)->getTable())
    ->where('user_id', Auth::user()->id);
})->get();

Given that I want an object with the union of both, I tested to run

$obj_merged = (object) array_merge((array) $user_owned_orgs, (array) $user_orgs);

then I only get one organization

{#1362 ▼
  #items: array:1 [▼
    0 => AppOrganization {#1390 ▶}
  ]
}

If I run

$user_owner_or_member = array_unique(array_merge($user_owned_orgs->toArray(),$user_orgs->toArray()), SORT_REGULAR);

then I got

array:2 [▼
  0 => array:7 [▼
    "id" => 1
    "name" => "organization1"
    "slug" => "organization1"
    "is_visible" => 0
    "user_id" => 1
    "created_at" => "2021-02-12T10:14:23.000000Z"
    "updated_at" => "2021-02-12T10:14:23.000000Z"
  ]
  1 => array:7 [▼
    "id" => 5
    "name" => "organization12"
    "slug" => "organization12"
    "is_visible" => 1
    "user_id" => 1
    "created_at" => "2021-03-01T08:34:25.000000Z"
    "updated_at" => "2021-03-01T08:34:25.000000Z"
  ]
]

While the result is correct in the sense of showing two records, it’s an array. That means the views, which were created to deal with objects, need to be modified (which would be fine but not ideal). Changing that to an object in the following to way isn’t also an option

(object) array_unique(array_merge($user_owned_orgs->toArray(),$user_orgs->toArray()), SORT_REGULAR);

In other words, what I am saying (and that might be the easiest option) is how can the query be changed to get all organizations the logged in user owns (organization.user_id = Auth::user()->id) and/or that same user is member of (organization_users.organization_id = organization.id AND organization_users.user_id = Auth::user()->id)?

Advertisement

Answer

You use Eloquent and better solution in Eloquent for merging two results is this:

$obj_merged = $user_owned_orgs->merge($user_orgs);

Now you have an Eloquent object with all useful properties.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement