Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gbdematos's avatar

Trouble in custom query

Hi! I'm having some trouble creating a query in laravel, if anyone has any tips I'd appreciate!

I have the following tables: "Item", "User", "Category", "ItemUser", and "CategoryItem".

An User can have multiple Items and vice-versa (belongs to Many), that's why I have the ItemUser pivot table.

An User can create categories (HasMany/BelongsTo), and add Items to them (CategoryItem).

If I do $user->items(), I get only the items included in the pivot ItemUser. I also want to include the items that are on categories this user created.

The final result would be Items = $user->items() merged with (only the items, and not the categories in) $user->categories()->with('items');

Is there any way to achieve this with one query?

0 likes
1 reply
JoaoPedroAS51's avatar

Try something like this:

$items = $user->items->toArray();

foreach($user->categories as $category)
{ 
    foreach($category->items as $citems)
    {
        array_push($items, $citems);
    }
}

//If you want an Array
$items 

//If you want a Collection
$items = collect($items);

Please or to participate in this conversation.