How to return different relation as the same name in an Api Resource
In my project I have set up multiple relationships like :
Model
public function foo()
{
return $this->hasMany(Bar::class);
}
public function fooSold()
{
return $this->hasMany(Bar::class)->where('sold', 1);
}
Controller
public function show()
{
$bar = Bar::with('foo')->first();
return new BarResource($bar);
}
public function showSold()
{
$bar = Bar::with('fooSold')->first();
return new BarResource($bar);
}
Resource
public function toArray($request)
return [
...
'foo' => Foo::collection($this->whenLoaded('foo')),
]
Returning the first function in my controller isn’t any problem. But how would I return the second one under the same name as ‘foo’ in my resource ?
'foo' => Foo::collection($this->whenLoaded'fooSold')),
'foo' => Foo::collection($this->whenLoaded'foo')),
This works but doesn’t seem like the right way to do it, since you have the same array keys twice.
What’s the best way of doing this ?
from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-return-different-relation-as-the-same-name-in-an-api-resource/
via Lzo Media
No comments:
Post a Comment