Skip to content

Commit

Permalink
Including Related Data
Browse files Browse the repository at this point in the history
  • Loading branch information
Ngonyoku committed Jan 7, 2024
1 parent 9daf286 commit 00decb0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
21 changes: 14 additions & 7 deletions app/Http/Controllers/Api/V1/CustomerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,18 @@ public function index(Request $request)
$filter = new CustomerFilter();

# Transform the filer
$queryItems = $filter->transform($request); //[['column', 'operator', 'value']]
$filterItems = $filter->transform($request); //[['column', 'operator', 'value']]

# Check for valid filter options
if (count($queryItems) == 0) {
return new CustomerCollection(Customer::paginate());
} else {
$customers = Customer::where($queryItems)->paginate();
return new CustomerCollection($customers->appends($request->query()));
$includeInvoices = $request->query('includeInvoices');
$customers = Customer::where($filterItems);

# If included voices is true, we fetch customers together with invoices
if ($includeInvoices) {
$customers = $customers->with('invoices');
}
return new CustomerCollection(
$customers->paginate()->appends($request->query())
);
}

/**
Expand All @@ -54,6 +57,10 @@ public function store(StoreCustomerRequest $request)
*/
public function show(Customer $customer)
{
$includeInvoices = request()->query('includeInvoices');
if ($includeInvoices) {
return new CustomerResource($customer->loadMissing('invoices'));
}
return new CustomerResource($customer);
}

Expand Down
3 changes: 2 additions & 1 deletion app/Http/Resources/V1/CustomerResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public function toArray(Request $request): array
'city' => $this->city,
'state' => $this->state,
'address' => $this->address,
'postalCode' => $this->postal_code
'postalCode' => $this->postal_code,
'invoices' => InvoiceResource::collection($this->whenLoaded('invoices'))
];
}
}

0 comments on commit 00decb0

Please sign in to comment.