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

simsar78's avatar

Get array of relationship in controller query not in blade.

Hello, i have three table:

  • Product
  • Shop
  • User

I need to list all product into the shop with list of user have the same product into shop.

Example Shop column -> id, product_id, user_id

$shops = Shop::get();

in Model I have this function:

return $this->HasMany(User::class, 'id', 'user_id)

But in this mode when load the blade have many access to database.

I need to have less access to database.

Thanks.

0 likes
1 reply
tykus's avatar

It is not clear what you are trying to achieve, but you must query the database if you need data.

How/where you query the database may be at the heart of your question? In that case, you can eager-load the relation(s) you need in the view:

$shops = Shop::with('users')->get();

Now you will have exactly two database queries (i) on the shops table and (ii) on the users table - Eloquent puts together the correct users with each individual Shop instance.

If you also want the Product instances, and assuming there is a similar products relation on the Shop model:

$shops = Shop::with('users', 'products')->get();
1 like

Please or to participate in this conversation.