title: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
body: <p>I get this error when saving a model with many to many relationship (Group and members).
  <strong>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (<code>propulse</code>.<code>group_user</code>, CONSTRAINT <code>group_user_group_id_foreign</code> FOREIGN KEY (<code>group_id</code>) REFERENCES <code>groups</code> (<code>id</code>) ON DELETE CASCADE</strong></p>
  <p>and some times when inserting values to the relation table:
  <strong>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (<code>propulse</code>.<code>group_user</code>, CONSTRAINT <code>group_user_group_id_foreign</code> FOREIGN KEY (<code>group_id</code>) REFERENCES <code>groups</code> (<code>id</code>) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into <code>group_user</code> (<code>group_id</code>, <code>user_id</code>) values (1, 4), (2, 4), (3, 4))</strong></p>
  <p>Note that the columns are inversed <strong>(<code>group_id</code>, <code>user_id</code>)</strong>
  In this example, the values 4 should be for column <strong>group_id</strong></p>
  <p>Here is my code:
  User.php</p>
  <pre><code>&lt;?php
  
  namespace App\Models;
  
  use Illuminate\Contracts\Auth\MustVerifyEmail;
  use Illuminate\Database\Eloquent\Factories\HasFactory;
  use Illuminate\Foundation\Auth\User as Authenticatable;
  use Illuminate\Notifications\Notifiable;
  
  class User extends Authenticatable
  {
      use HasFactory, Notifiable;
  /**
       * The attributes that are mass assignable.
       *
       * @var array
       */
      protected $fillable = [
          'username',
          'email',
          'password',
      ];
  
      /**
       * The attributes that should be hidden for arrays.
       *
       * @var array
       */
      protected $hidden = [
          'password',
          'remember_token',
      ];
  
      /**
       * The attributes that should be cast to native types.
       *
       * @var array
       */
      protected $casts = [
          'email_verified_at' =&gt; 'datetime',
      ];
      
      public function groups() {
          return $this-&gt;belongsToMany(
              Group::class,
              'group_user',
              'group_id',
              'user_id'
          );
      }
  
  public function propulsedGroups() {
          return $this-&gt;hasMany(Group::class);
      }
  }
  </code></pre>
  <p>Group.php</p>
  <pre><code>&lt;?php
  
  namespace App\Models;
  
  use Illuminate\Database\Eloquent\Factories\HasFactory;
  use Illuminate\Database\Eloquent\Model;
  
  class Group extends Model
  {
      use HasFactory;
  
      protected $table    = 'groups';
      protected $fillable = [
          'logo',
          'name',
          'description',
          'propulser_id'
      ];
  
      public function users() {
          return $this-&gt;belongsToMany(
              User::class,
              'group_user',
              'user_id',
              'group_id'
          );
      }
  
  public function propulser() {
          return $this-&gt;belongsTo(User::class, 'propulser_id');
      }
  
  }
  </code></pre>
  <p>users_table</p>
  <pre><code>&lt;?php
  
  use Illuminate\Database\Migrations\Migration;
  use Illuminate\Database\Schema\Blueprint;
  use Illuminate\Support\Facades\Schema;
  
  class CreateUsersTable extends Migration
  {
      /**
       * Run the migrations.
       *
       * @return void
       */
      public function up()
      {
          Schema::create('users', function (Blueprint $table) {
              $table-&gt;increments('id')-&gt;unsigned();
              $table-&gt;string('username')-&gt;unique();
              $table-&gt;string('email')-&gt;unique();
              $table-&gt;timestamp('email_verified_at')-&gt;nullable();
              $table-&gt;string('password');
              $table-&gt;string('code')-&gt;unique();
              $table-&gt;enum('status', ['active', 'blocked', 'desactivated']);
              $table-&gt;enum('type', ['member', 'propulser'])-&gt;default('member');
              $table-&gt;rememberToken();
              $table-&gt;timestamps();
          });
      }
  
      /**
       * Reverse the migrations.
       *
       * @return void
       */
      public function down()
      {
          Schema::dropIfExists('users');
      }
  }
  </code></pre>
  <p>groups_table</p>
  <pre><code>&lt;?php
  
  use Illuminate\Database\Migrations\Migration;
  use Illuminate\Database\Schema\Blueprint;
  use Illuminate\Support\Facades\Schema;
  
  class CreateGroupsTable extends Migration
  {
      /**
       * Run the migrations.
       *
       * @return void
       */
      public function up()
      {
          Schema::create('groups', function (Blueprint $table) {
              $table-&gt;increments('id')-&gt;unsigned();
              $table-&gt;string('name');
              $table-&gt;longText('description');
              $table-&gt;string('logo')-&gt;nullable();
              //$table-&gt;string('cover')-&gt;nullable();
              $table-&gt;string('code')-&gt;unique();
              $table-&gt;integer('propulser_id')-&gt;unsigned();
              $table-&gt;foreign('propulser_id')-&gt;references('id')-&gt;on('users')
                  -&gt;onUpdate('cascade')-&gt;onDelete('cascade');
              $table-&gt;timestamps();
          });
      }
  
      /**
       * Reverse the migrations.
       *
       * @return void
       */
      public function down()
      {
          Schema::dropIfExists('groups');
      }
  }
  </code></pre>
  <p>group_user_table</p>
  <pre><code>&lt;?php
  
  use Illuminate\Database\Migrations\Migration;
  use Illuminate\Database\Schema\Blueprint;
  use Illuminate\Support\Facades\Schema;
  
  class GroupUser extends Migration
  {
      /**
       * Run the migrations.
       *
       * @return void
       */
      public function up()
      {
          Schema::create('group_user', function (Blueprint $table)
          {
              $table-&gt;increments('id')-&gt;unsigned();
              $table-&gt;integer('user_id')-&gt;unsigned();
              $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users')
                  -&gt;onUpdate('cascade')-&gt;onDelete('cascade');
              $table-&gt;integer('group_id')-&gt;unsigned();
              $table-&gt;foreign('group_id')-&gt;references('id')-&gt;on('groups')
                  -&gt;onUpdate('cascade')-&gt;onDelete('cascade');
  
          });
      }
  
      /**
       * Reverse the migrations.
       *
       * @return void
       */
      public function down()
      {
          Schema::dropIfExists('group_user');
      }
  }
  </code></pre>
  <p>GroupsController.php function store()</p>
  <pre><code>/**
       * Store a newly created resource in storage.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return \Illuminate\Http\Response
       */
      public function store(Request $request)
      {
          $this-&gt;validate($request, [
              'name'          =&gt; 'required',
              'description'   =&gt; 'required',
              'logo'   =&gt; validate_image(),
              'propulser_id' =&gt; '',
              'members'   =&gt; ''
          ], [], [
              'name'      =&gt; 'Name',
              'description'     =&gt; 'Description',
              'logo'  =&gt; 'Logo',
              'propulser_id' =&gt; 'Propulser',
              'members'   =&gt; 'members'
          ]);
  
          $letter = chr(rand(65,90));
  
          $code = IdGenerator::generate(['table' =&gt; 'users', 'field' =&gt; 'code', 'length' =&gt; 10, 'prefix' =&gt; $letter]);
  
          $group = new Group;
          $group-&gt;code = $code;
          $group-&gt;name = $request-&gt;name;
          $group-&gt;description = $request-&gt;description;
          $group-&gt;propulser_id = $request-&gt;propulser_id;
          if (request()-&gt;hasFile('logo')) {
              $group-&gt;logo = Up::upload([
                  'new_name'      =&gt; 'group',
                  'file'          =&gt; 'logo',
                  'path'          =&gt; 'groups',
                  'upload_type'   =&gt; 'single',
                  'delete_file'   =&gt; Group::find($request-&gt;id) != null ? Group::find($request-&gt;id)-&gt;logo : ''
                  ]);
              }
  
              $user = User::find($request-&gt;propulser_id);
              $user-&gt;type = &quot;propulser&quot;;
              $user-&gt;save();
  
              $group-&gt;save();
  
              $group-&gt;users()-&gt;attach($request-&gt;members);
  
          session()-&gt;flash('success', 'Added successfully');
          return redirect(aurl('groups'));
  }
  </code></pre>
  <p>Create group view:</p>
  <pre><code>&lt;section id=&quot;create-group&quot;&gt;
      &lt;div class=&quot;card&quot;&gt;
          &lt;div class=&quot;card-header&quot;&gt;&lt;i class=&quot;fa fa-align-justify&quot;&gt;&lt;/i&gt; {!! $title !!}&lt;/div&gt;
          &lt;div class=&quot;card-body&quot;&gt;
              {!! Form::open(['url' =&gt; aurl('groups'), 'files' =&gt; true]) !!}
              &lt;div class=&quot;form-group&quot;&gt;
                  &lt;div class=&quot;avatar-upload&quot;&gt;
                      &lt;div class=&quot;avatar-edit&quot;&gt;
                          {!! Form::file('logo', ['class'=&gt;'form-control', 'id' =&gt; 'imageUpload']) !!}
                          &lt;label for=&quot;imageUpload&quot;&gt;&lt;i class=&quot;fas fa-pencil-alt&quot;&gt;&lt;/i&gt;&lt;/label&gt;
                      &lt;/div&gt;
                      &lt;div class=&quot;avatar-preview&quot;&gt;
                          &lt;div id=&quot;imagePreview&quot; style=&quot;background-image: url(http://i.pravatar.cc/500?img=7);&quot;&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class=&quot;form-group&quot;&gt;
                  {!! Form::label('name', 'Group name') !!}
                  {!! Form::text('name', old('name'), ['class' =&gt; 'form-control']) !!}
              &lt;/div&gt;
              &lt;div class=&quot;form-group&quot;&gt;
                  {!! Form::label('description', 'Group description') !!}
                  {!! Form::textarea('description', old('description'), ['class' =&gt; 'form-control']) !!}
              &lt;/div&gt;
              &lt;div class=&quot;form-group&quot;&gt;
                  {!! Form::label('propulser_id_id', 'propulser') !!}
                  {!! Form::select('propulser_id', $users, old('propulser_id'),['class' =&gt; 'form-control']) !!}
              &lt;/div&gt;
  
                 &lt;div class=&quot;form-group&quot;&gt;
                  {!! Form::label('members', 'Members') !!}
                  {!! Form::select('members[]', $users, old('members'),['multiple' =&gt; 'multiple','class' =&gt; 'js-example-basic-multiple form-control']) !!}
                 &lt;/div&gt;
  
              {!! Form::submit('Create', ['class' =&gt; 'btn btn-primary']) !!}
              {!! Form::close() !!}
          &lt;/div&gt;
        &lt;/div&gt;
  &lt;/section&gt;
  </code></pre>
  <p>I hope someone could help.
  Thanks in advance.</p>