skip to Main Content

I have two tables that are connected with a pivot table.

shows:

+----+--------+
| id | show   |
+----+--------+
|  1 | show1  |
|  2 | show2  |
|  3 | show3  |
+----+--------+

draft_types:

+----+--------+
| id | type   |
+----+--------+
|  1 | type1  |
|  2 | type2  |
|  3 | type3  |
+----+--------+

show_draft_types:

+---------+---------------+
| show_id | draft_type_id |
+---------+---------------+
|  1      | 1             |
|  1      | 2             |
|  1      | 3             |
+---------+---------------+

So essentially a show has many different draft types and here’s the relationship that I’m using in eloquent for shows:

public function draft_types()
{
    return $this->belongsToMany('AppModelsDraftTypes', 'show_draft_types', 'show_id', 'draft_type_id');
}

The problem is whenever I do:

Shows::where('id', 1)->with(['draft_types'])->first()

I get this:

{
    id: 1,
    show: "show1",
    draft_types: [
        {
            id: 1,
            type: "type1"
        },
        {
            id: 2,
            type: "type2"
        },
        {
            id: 3,
            type: "type3"
        }
    ]
}

What I want to get is this:

{
    id: 1,
    show: "show1",
    draft_types: [
        "type1",
        "type2",
        "type3"
    ]
}

Is there a way to do this with eloquent relationships?

2

Answers


  1. You could add an appended attribute to the Show model and an accessor for the desired array:

    // Show.php
    
    class Show extends Model
    {
        protected $appends = ['draft_types_array'];
    
        public function draft_types()
        {
            return $this->belongsToMany('AppModelsDraftTypes', 'show_draft_types', 'show_id', 'draft_type_id');
        }
    
        public function getDraftTypesArrayAttribute()
        {
            return $this->draftTypes->pluck('type')->toArray();
        }
    }
    

    Usage:

    
    $show = Shows::where('id', 1)->with(['draft_types'])->first();
    
    dd($show->draft_types_array);
    
    
    // Outputs: 
    // [
    //   "type1",
    //   "type2",
    //   "type3"
    //  ]
    
    
    Login or Signup to reply.
  2. You can use the method makeHidden().

    $users = $users->makeHidden(['address', 'phone_number']);
    

    [https://laravel.com/docs/11.x/eloquent-collections#method-makeHidden][1]

    [1]: Laravel Docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search