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

sardar1592's avatar

Many to Many Relationships in an API Resource

How do we load many to many relationships on API resources? I have two plot and feature models that are in a many to many relationship.

I am getting an array of items like this only instead of full objects.

"features": [ 29, 28, 23, 22, ]

My PlotsController:

  $plots = Plot::latest()->get();

  return PlotResource::collection($plots); 

My Plot Model:

`protected $casts = [ 'images' => 'array', 'features' => 'array'

];`

public function features(){

  return $this->belongsToMany(Feature::class);

}`

My Feature model:

` public function plots(){

  return $this->belongsToMany(Plot::class);

}`

in my plot resource, I am calling the relations like this:

'features' => $this->features,

In my plots table, I am saving a features array in this field:

$table->text('features')->nullable(); (in other tables I am also using json as column type)

I want every feature in the relation to show like this:

{ "id": 31, "feature": "Lake Facing", "created_at": "2021-11-14T07:00:31.000000Z", "updated_at": "2021-11-14T07:00:31.000000Z" },

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

That isn't a relationship? It's just a column

Create an actual table for features instead. What is the features model pointing at?

sardar1592's avatar

@Sinnbeck Thanks for the hint. The features table was already there. I have figured out what I was doing wrong. I was saving the features ids on the plots table as they were coming in the request. I am now just using them to attach to the plots and have deleted the features column on the plots table. Everything is back to normal now with both features and plots showing reciprocal relationships on the resources alright.

Sinnbeck's avatar

@sardar1592 yeah that sounds correct. If it was solved, please consider marking a best answer to set the thread as solved

Please or to participate in this conversation.