mercredi 28 novembre 2018

How to organize my API based on Laravel 5

I have usual resource UserController

UserController extends Controller {

   public function index() {  /**... some code */ }

   public function store(Request $request) {  /**... some code */ }

   public function show(User $user) {  /**... some code */ }

   public function update(Request $request, User $user) {  /**... some code */ }

   public function destroy(User $user) {  /**... some code */ }

}

User extends Model {
   protected $fillable = [ 'name', 'email'];
}

And I have a child resource ContactController

ContactController extends Controller {

   public function index(User $user) {  /**... some code */ }

   public function store(Request $request, User $user) {  /**... some code */ }

   public function show(User $user, Contact $contact) {  /**... some code */ }

   public function update(Request $request, User $user, Contact $contact) {  /**... some code */ }

   public function destroy(User $user, Contact $contact) {  /**... some code */ }

}

Contact extends Model {
   protected $fillable = [ 'phones', 'user_id' ];
}

In my routes.php

Route::apiResource('users', 'UserController');

Route::apiResource('users.contacts', 'ContactController');

In my case, I can create thought API only one contact for the user. Make request to

POST api/users/12/contacts After that, I can get this contact GET api/users/12/contacts/11 And a client can create as many as possible contacts use POST api/users/12/contacts But my user can have only one contact.

Actual I can solve this by adding validation, but I think this trick is not solving the problem correctly



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire