phplaravelrelationshippluck

Laravel Pluck from 'with relation'


Need to have a pluck from with relation. I'm sharing code below.

My controller:

$type = StandType::with(['brieftype' => function($q) use ($brief_id){
        $q->where('brief_id', $brief_id);
      }])->get()->keyBy('name');

My Model:

 public function brieftype(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany('App\Models\BriefType', 'key', 'name');
    }

I want to response like that:

[Blabla] => {
  'title' => 'my title',
  'name' => 'my name'
  'brieftype' => ['name1', 'name2', 'name3', 'name4']
}

Solution

  • Give this a try.

    $types = $types->map(function ($type) {
        $type->brieftype = $type->brieftype->pluck('name')->toArray();
        return $type;
    })->toArray();