@samehdev Hi, yes there is an easy way to do it. You can use eager loading in your controller like so:
Your Controller:
class ExampleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
*/
public function index()
{
return ExampleResource::collection(Example::all()->load('relation', 'anotherRelation'));
}
}
Then you are going to need to define an Api Resource for your Model like the following:
class Example extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'unique_id' => $this->unique_id,
'comments' => $this->comments,
'owner_name' => $this->owner_name,
'guest_count' => $this->guest_count,
'room_count' => $this->room_count,
'status' => $this->status,
'total_amount' => $this->total_amount,
'total_due' => $this->total_due,
'currency' => $this->currency,
'relation' => AnotherExampleResource::collection($this->whenLoaded('relation')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at
];
}
}
Notice the whenLoaded method in the response. This will conditionally load the relation of the model only if you have eager loaded it somewhere, in our case the controller's index method.
A reference may be found here: https://laravel.com/docs/8.x/eloquent-resources#introduction and here https://laravel.com/docs/8.x/eloquent-resources#conditional-relationships