title: Retrieve and create data in many to many relationship in Laravel 8
body: <p>I want to create a user through a form. In the form, I will select the user type. Accordingly, the user is created, and it will be saved in the database. I can do everything, but I don't understand how to show user role in select menu with controller and create the user. I have three separate tables. One is for the user, the other is for the role, and the other is the user role. Please help me</p>
  <p><strong>User Model</strong></p>
  <pre><code>class User extends Model
  {
      public function user(){
          return $this-&gt;belongsToMany(Role::class, 'roles_users');
      }
  }
  </code></pre>
  <p><strong>Roles Model</strong></p>
  <pre><code>
  class Role extends Model
  {
      public function user(){
          return $this-&gt;belongsToMany(User::class, 'roles_users');
      }
  }
  </code></pre>
  <p><strong>Controller</strong></p>
  <pre><code>class FormController extends Controller
  {
      public function index() {
          $user = User::find(1);  
   
          $role_ids = [1, 2];
  
          $user-&gt;roles()-&gt;attach($role_ids);
      }
  }
  </code></pre>
  <p><strong>View</strong></p>
  <pre><code>&lt;form action=&quot;{{route('store.data')}}&quot; method=&quot;post&quot;&gt;
      @csrf
      &lt;label for=&quot;&quot;&gt;User Type&lt;/label&gt;
      &lt;select name=&quot;usertype&quot;&gt;&lt;/select&gt;
      &lt;option value=&quot;&quot;&gt;Select Usertype&lt;/option&gt;
      @foreach($data as $user)
      &lt;option value=&quot;{{$user-&gt;id}}&quot;&gt;{{$user-&gt;name}}&lt;/option&gt;
      @endforeach
      &lt;label for=&quot;&quot;&gt;Username&lt;/label&gt;
      &lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
      &lt;button type=&quot;submit&quot;&gt;Add User&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>