How can I do select some columns of a relation in the resources model?

687 views Asked by At

I have a model resource and I am calling $this->tags inside of it

This resource returns as the following:

"data": {
  "some_keys"  : ...,
  "some_keys2" : ...,
  "tags":[
           {
             "id": 1,
             "name": "c++",
             "parent_id": null,
             "type": null,
             "created_at": "2020-09-27 20:37:57",
             "updated_at": "2020-09-27 20:37:57",
             "pivot": {
                "task_id": 43,
                "skill_id": 1
             }
           }
        ]

I want to do as follows:

"data": {
  "some_keys"  : ...,
  "some_keys2" : ...,
  "tags": [
            {
              "id": 1,
              "name": "c++"
            }
          ]

My resources Model:

public function toArray($request)
{
    $data = parent::toArray($request);
    $data["tags"] = $this->tags;
    return $data;
}

My Task Model:

public function tags(){
    return $this->belongsToMany(Skill::class, 'task_skills', 'task_id', 'skill_id');
}

How can I reduce some columns of tags in the resources model?

I solved it this way:

$data["tags"] = $this->tags->makeHidden(['pivot','created_at','updated_at','type','parent_id']);
1

There are 1 answers

4
Prafulla Kumar Sahu On

There are quite a few collection methods, which you are trying to achieve based on that you can use.

pluck

$collection = collect([
    [
        'speakers' => [
            'first_day' => ['Rosa', 'Judith'],
            'second_day' => ['Angela', 'Kathleen'],
        ],
    ],
]);

$plucked = $collection->pluck('speakers.first_day');

$plucked->all();

// ['Rosa', 'Judith']

only

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

get

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

// Taylor

If you always want to keeps some attributes hidden you can use

protected $hidden = ['parent_id', 'created_at']; in your model