title: API RESTful Laravel 6.x Best Practice for Many to Many Relatioship
body: <p>I'm developing an API with Laravel 6. </p>
  
  <p>I've got 2 models: </p>
  
  <blockquote>
    <p>card -> table cards with card_id ecc.</p>
    
    <p>user -> table users with user_id ecc.</p>
  </blockquote>
  
  <p>I've defined into models many to many relationships </p>
  
  <p>User.php </p>
  
  <pre><code>public function cards()
  {
      return $this-&gt;belongsToMany('App\Models\v1\Card');
  }
  </code></pre>
  
  <p>Card.php</p>
  
  <pre><code>public function users() {
      return $this-&gt;belongsToMany('App\Models\v1\User');
  }
  </code></pre>
  
  <p>The pivot table is called card_user .</p>
  
  <p>Now I've created routes for single entities: </p>
  
  <pre><code>Route::resource('v1/users', 'v1\UsersController');
  Route::resource('v1/cards', 'v1\CardsController');
  </code></pre>
  
  <p>and I need to develop routes and controller for insert and delete rows from pivot table.</p>
  
  <p>What is the best practice for this issue? </p>
  
  <p>I try to solve this with a special controller that respond to a specific endpoint:</p>
  
  <pre><code>Route::resource('v1/cards/{id}/users', 'v1\CardsUsersController')-&gt;only([
      'index', 'store', 'destroy'
  ]);
  </code></pre>
  
  <p>But when I need to store information I need to pass the ids of card and user into the URL and as object in post body like so:</p>
  
  <pre><code>[
      'user_id' =&gt; $userId,
      'card_id' =&gt; $cardId
  ]
  </code></pre>
  
  <p>Exists a better way to do this?</p>
  
  <p>Thanks a lot!</p>