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

Kabir1993's avatar

How do I get value inside collection of many to many relationship

Hello,

I have three tables

---products--- id name desc

---photos--- id image

---product_photos id product_id photo_id

In my Product model I put;

public function productPhotos() { return $this->belongsToMany(Photo::class, 'product_photos')->withTimestamps(); }

In my Photo model I put;

public function productPhotos() { return $this->belongsToMany(Product::class, 'product_photos')->withTimestamps(); }

now I getting values like:

{"id":1,"file":"images/Xw8LCg250jZnIcPi7QL4zFtvmaItVdonPUszVJik.png","created_at":"2021-03-09T00:14:27.000000Z","updated_at":"2021-03-09T00:14:27.000000Z","pivot":{"product_id":1,"photo_id":1,"created_at":"2021-03-09T00:14:27.000000Z","updated_at":"2021-03-09T00:14:27.000000Z"}} {"id":3,"file":"images/3wsEonZS2sIhEBHJlA1cFizr9SUfcMeTGp7G5Swd.jpg","created_at":"2021-03-09T00:47:15.000000Z","updated_at":"2021-03-09T00:47:15.000000Z","pivot":{"product_id":1,"photo_id":3,"created_at":"2021-03-09T05:47:40.000000Z","updated_at":"2021-03-09T05:47:40.000000Z"}}

Here my question is I don't know how Do I get only image column in my collection Thanks in advance

0 likes
4 replies
Kabir1993's avatar

thanks for reply but it returning me the array ["images/jYM52trkCNW3sDQbTztiqUZlET90p7nwdZSlWh5Q.png"] how do I get value like images/jYM52trkCNW3sDQbTztiqUZlET90p7nwdZSlWh5Q.png

this is my model code public function photo() { $image = $this->photoProduct()->pluck('file'); return $image; }

jlrdw's avatar

Query what you need from database instead of using a collection.

Please or to participate in this conversation.