Search code examples
laravelrelationshiphas-and-belongs-to-manylaravel-nova

Laravel BelongsToMany with array of ids as an attribute instead of individual id


Given:

"users" table:

[{
 id: 1,
 school_ids: [1, 2, 3] // text type cast as array
}]

Then:

"schools" table:

[{
  id: 1,
  name: 'school 1",
},
{
  id: 2,
  name: 'school 2",
},
{
  id: 3,
  name: 'school 3",
}]

I currently have a relationship in my User model as:

public function schools() {
  return $this->belongsToMany(School::class, 'school_ids');
}

which currently doesn't work.

  1. I was wondering if I can make it work where if it reads the school_ids it will cast it as an array and calling User::schools() will give me a collection of School Model?
  2. If #1 can be done, I wonder if I can implement it on Laravel nova (?)

Solution

  • So to make my life easier, I decided to create a pivot table instead that links the school and user.