How to get properies of a relationship as comma separated values in laravel?

I have a ManyToMany relationship for example Facility and Home so here is the example of the relationship:

public function facility()
{
    return $this->belongsToMany(facility::class)->withPivot('is_free');
}

and in facility I have:

public function home()
{
   return $this->belongsToMany(Home::class)->withPivot('is_free');
}

and in some controller I do like below :

$data = Home::with('facility')->get;

it gives me the result like below :

{
    name: example,
    id: 1,
    facility: {
        id: 1,
        name:item1,
    },
    {
        id: 1,
        name:item1,
    },
    {
        id: 1,
        name:something,
    }
}

now i want it comma separated like below :

{   
    name:example,
    id : 1,
    some other fileds ,
    ,
    , 
         facility: {item1,item2,item3,item4,. . .
    }
}

so I want them comma separated and only pick some certain columns from it

2 answers

  • answered 2019-09-11 11:54 Kishore Kadiyala

    If you want to restrict the results for facility, you can do this.

    public function facility()
    {
        return $this->belongsToMany(facility::class)->withPivot('is_free')->where('some_field','some_value');
    }
    

    if you want to join the results by comma, you can do this.

    foreach($homes as $home) {
      $home->computed_field = $home->facility->pluck('name')->implode(',');
    }
    

  • answered 2019-09-12 06:34 Kevin Bui

    I recommend using a custom attribute for this.

    public function getFacilityDataAttribute()
    {
        return implode(", ", $this->facility->getAttributes());
    }
    

    And inside Home class:

    class Home extends Model
    {
        protected $appends = ['facility_data'];
    }