Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API Architecture - best practices

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!

like image 458
Ben Southall Avatar asked Dec 08 '25 10:12

Ben Southall


1 Answers

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}
like image 144
Brian Lee Avatar answered Dec 11 '25 11:12

Brian Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!