There is a way in Laravel to load a relationship with only 1 column value and to have it as an array?
I have a belongsToMany relationship from Page Model to Country, State models.
public function countries(){
return $this->belongsToMany(Country::class, 'page_country', 'page_id', 'country_id');
}
public function states(){
return $this->belongsToMany(State::class, 'page_state', 'page_id', 'state_id');
}
When I load these relationships I need to get the result as an array of values [1,2,3,4] (ids of the related model). In other words, I need to load only id of states and countries for my Page
So instead of key-value pair:
[
'states' => ['id' => 1, 'id' => 2, ...],
'countries' => ['id' => 1, 'id' => 2, ...]
]
I want to achieve this:
[
'states' => [1, 2, ...],
'countries' => [1, 2, ...]
]
What I'm doing currently is:
Load the relationship:
public function view(Page $page){
$page->load([
'countries:id',
'states:id'
]);
//Transform to get array of ids for each relation
$page->countries->transform(function($item){
return $item->id;
});
$page->states->transform(function($item){
return $item->id;
});
//and return as json
return response()->json($page)
}
Maybe there is a better way to achieve this? Because when I need to load 10 relationships, I need to run 10 transforms functions.
$page->countries->pluck('id')->toArray()or$page->countries->modelKeys()for collections laraveldaily.com/…