I'm implementing an API that can create clients and create contacts. Contacts may be associated with a client.
I have my ClientController.php with all the CRUD methods.
I also have a ContactController.php with all the CRUD methods.
I want to allow a contact to be created and assigned to a client all in the one API call.
I was thinking the best way would be add a function to my ClientController and call it via the API: /api/client/6/addContact
public function addContact($clientId, Request $request) {
$contact = new Contact($request->all())->save();
$client = Client::find($clientId)->attach($contact->id);
return response()->json(null, 200);
}
But my issue is that the method to add a contact (and validate it) is in the ContactController.php, so i'm doubling up on the code. How can I use the ContactController@store method from the ClientController@addContact ?
Is there a common API architecture for these types of issues?
Thanks!
I'd suggest using a nested api resource route:
// generate the controller class
php artisan make:controller Api/ContactController --api
// create the route definitions
Route::apiResource('clients.contacts', 'ContactController');
The above creates the routes:
GET /clients/{client}/contacts
POST /clients/{client}/contacts
GET /clients/{client}/contacts/{contact}
PUT/PATCH /clients/{client}/contacts/{contact}
DELETE /clients/{client}/contacts/{contact}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With