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
You could add an appended attribute to the
Show
model and an accessor for the desired array:Usage:
You can use the method
makeHidden()
.[https://laravel.com/docs/11.x/eloquent-collections#method-makeHidden][1]
[1]: Laravel Docs