Sync method won't work using many to many relationship Laravel 5.2
<p>I'm trying to attach the array of items that I have in my form to my junction table. I already given all the values stored in my tables using <code>foreach</code> loop. I loop this all in my select list.</p>

<p>Retrieve all records in tables:</p>

<pre><code>$resultRecipient = DB::table('users')-&gt;where('id', '!=', Auth::id())-&gt;get();
return view ('document.create')-&gt;with('resultRecipient', $resultRecipient);
</code></pre>

<p>Form:</p>

<pre><code>&lt;div class = "form-group"&gt;

    &lt;label for = "recipient_id" class = "control-label"&gt;To:&lt;/label&gt;

    &lt;select name = "recipient_id[]" multiple class = "form-control" id = "myUserList"&gt;

            @foreach ($resultRecipient as $list)
                &lt;option value = "{{ $list-&gt;id }}"&gt;{{ $list-&gt;username }}&lt;/option&gt;
            @endforeach

    &lt;/select&gt;

&lt;/div&gt;
</code></pre>

<p>Migration:</p>

<p><strong>users</strong></p>

<p>-id</p>

<p>-username</p>

<p>-password</p>

<p><strong>documents</strong></p>

<p>-id</p>

<p>-title</p>

<p>-content</p>

<p>-category_id - FK</p>

<p><strong>recipients_documents</strong> (junction table)</p>

<p>-id</p>

<p>-senderUserId - FK reference to <strong>users</strong></p>

<p>-recipientUserId - FK reference to <strong>users</strong></p>

<p>-docu_id - FK reference to <strong>documents</strong></p>

<p>My Models:</p>

<p>Document
    

<pre><code>namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{    

public function recipients()
{
    return $this-&gt;belongsToMany('Models\User');
}
}
</code></pre>

<p>User:</p>

<pre><code>&lt;?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class User extends Model implements AuthenticatableContract
{
use Authenticatable;

public function documents()
{
    return $this-&gt;belongsToMany('Models\Document');
}
}
</code></pre>

<p>DocumentController:</p>

<pre><code>public function postDocuments(Request $request)
{

    $this-&gt;validate($request,
    [
        'title' =&gt; 'required|alpha_dash|max:255',
        'content' =&gt; 'required',
        'category_id' =&gt; 'required',
        'recipient_id' =&gt; 'required',
    ]);


    $document = new Document();
                                //Request in the form
    $document-&gt;title = $request-&gt;title;
    $document-&gt;content = $request-&gt;content;
    $document-&gt;category_id = $request-&gt;category_id;

    $document-&gt;save();
    $document-&gt;recipients()-&gt;sync($request-&gt;recipient_id, false);


    return redirect()-&gt;back();  
}
</code></pre>

<p>When I'm trying to attach the request in my form which is <code>recipient_id</code> but it error says. I just created a new folder in app named <strong>Models</strong></p>

<blockquote>
  <p>Class 'Models\User' not found</p>
</blockquote>

<p>Can anyone tell why I get this error? Any help would appreciated!</p>

<p>Cheers</p>

<p><strong>UPDATE 1</strong></p>

<p>I solved this error followed steps by @jaysingkar. But when I try to <code>sync</code> this after hitting the submit button it gives me a error.</p>

<blockquote>
  <p>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'webdev.document_user' doesn't exist (SQL: select <code>user_id</code> from <code>document_user</code> where <code>document_id</code> = 15)</p>
</blockquote>

<p>But it insert in the document tables but in my juction table won't insert that I want to attach.</p>

<p><strong>UPDATE 2</strong>
Thanks @jaysingkar and @mydo47 for the help and tips that you given. I already create document_user table (junction) I added a another <strong>Foreign Key</strong> which refenreces to <strong>users</strong> table.</p>

<p>Screenshot:</p>

<p><a href="https://i.stack.imgur.com/GOMdC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GOMdC.jpg" alt="Many to many"></a></p>

<p>As you can see here I linked two foreign key in the junction table. I want to insert the current user that logged-in in the <code>user_id</code> column. I have a form here which loop through my database records except the id of the current user that logged in.</p>

<p>Form:</p>

<pre><code>&lt;div class = "form-group"&gt;

&lt;label for = "recipient_id" class = "control-label"&gt;To:&lt;/label&gt;

&lt;select name = "recipient_id[]" multiple class = "form-control" id = "myUserList"&gt;

        @foreach ($resultRecipient as $list)
            &lt;option value = "{{ $list-&gt;id }}"&gt;{{ $list-&gt;username }}&lt;/option&gt;
        @endforeach

&lt;/select&gt;
</code></pre>

<p></p>

<p>Migration for junction table:</p>

<pre><code>public function up()
 {
    Schema::create('document_user',function (Blueprint $table)
    {
        $table-&gt;increments('id');
        $table-&gt;integer('user_id')-&gt;unsigned();
        $table-&gt;integer('recipientUserId')-&gt;unsigned();
        $table-&gt;integer('document_id')-&gt;unsigned();

        $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade');
        $table-&gt;foreign('recipientUserId')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade');
        $table-&gt;foreign('document_id')-&gt;references('id')-&gt;on('documents')-&gt;onDelete('cascade');
        $table-&gt;dateTime('dateReceived')-&gt;default(DB::raw('CURRENT_TIMESTAMP'));
    });
 }
</code></pre>

<p>Document Controller:</p>

<pre><code>public function postDocuments(Request $request)
{

    $this-&gt;validate($request,
    [
        'title' =&gt; 'required|alpha_dash|max:255',
        'content' =&gt; 'required',
        'category_id' =&gt; 'required',
        'recipient_id' =&gt; 'required',
    ]);


    $document = new Document();
                                //Request in the form
    $document-&gt;title = $request-&gt;title;
    $document-&gt;content = $request-&gt;content;
    $document-&gt;category_id = $request-&gt;category_id;

    $document-&gt;save();
    $document-&gt;recipients()-&gt;sync($request-&gt;recipient_id, false);


    return redirect()-&gt;back();  
}
</code></pre>

<p>But when I try to submit it says. Is this valid that I can linked PK to two FK? I can insert the selected list in the <strong>document_user</strong> table but how can I insert the current user? Thanks for the help</p>

<blockquote>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (<code>webdev</code>.<code>document_user</code>, CONSTRAINT <code>document_user_recipientuserid_foreign</code> FOREIGN KEY (<code>recipientUserId</code>) REFERENCES <code>users</code> (<code>id</code>) ON DELETE CASCADE) (SQL: insert into <code>document_user</code> (<code>document_id</code>, <code>user_id</code>) values (27, 10))</p>
</blockquote>

<p><strong>UPDATE 3</strong></p>

<p>I already get rid of the error so I created a <code>unsignedInteger</code> this column where the current user id will insert name <code>sender_id</code></p>

<p>Migration update:</p>

<pre><code> Schema::create('document_user',function (Blueprint $table)
    {
        $table-&gt;increments('id');
        $table-&gt;integer('user_id')-&gt;unsigned();
        $table-&gt;integer('document_id')-&gt;unsigned();

        $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade');
        $table-&gt;foreign('document_id')-&gt;references('id')-&gt;on('documents')-&gt;onDelete('cascade');

        $table-&gt;unsignedInteger('sender_id')-&gt;nullable();
        $table-&gt;foreign('sender_id')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade');


        $table-&gt;dateTime('dateReceived')-&gt;default(DB::raw('CURRENT_TIMESTAMP'));
    });
</code></pre>

<p>I can get the id of the current user that logged in. But I'm thinking how can I insert the id based on the submit of the user.</p>

<p>DocumentController:</p>

<pre><code>public function getDocuments()
{
    //GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
    $resultRecipient = DB::table('users')-&gt;where('id', '!=', Auth::id())-&gt;get();


    //GETTING ALL THE CATEGORIES.
    $resultCategory = DB::table('categories')-&gt;get();


    //VIEW
    return view ('document.create')-&gt;with('resultRecipient', $resultRecipient)-&gt;with('resultCategory', $resultCategory);

    if(\Auth::user()-&gt;id)
    {
        echo "You get the id";
    }
    else
    {
        echo "Failed";
    }

}
</code></pre>

<p>Database Screenshot:</p>

<p><a href="https://i.stack.imgur.com/JFVsv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFVsv.jpg" alt="enter image description here"></a></p>