How to create an accessor for pivot field in larval 10.x?

40 Views Asked by At

I have two models:

  • User
  • Place
    and a Pivot as:
  • Role(user_id, place_id, type)
    and an example of type is "["manager", "reception"]" and i want to change this value to collection when retriving as: Place::find(1)->users[0]->pivot->type

i add this method but it doesn't work and return string:

    public function getTypeAttribute($value){
        return collect(json_decode($value));
    }
1

There are 1 best solutions below

0
mostafa amiri On BEST ANSWER

I forgot to use using. It should be like this: $this->belongsToMany(Place::class, 'roles', 'place_id', 'user_id')->using(Role::class)->withPivot('type');