0

I'm trying to delete a user but there is ForeignKey constraints that I also need to delete.

In my User model, I have

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    public $incrementing = false;

    protected $fillable = [
        'name', 
        'email', 
        'password',
        'timezone', 
        'profile_picture', 
        'notification_key'
    ];

    protected $hidden = [
        'password', 
        'pivot', 
        'admin'
    ];

    public static function boot()
    {
        parent::boot();

        static::creating(function ($instance) {
            $instance->id = Uuid::uuid4();
        });
    }

    public function groups()
    {
        return $this->belongsToMany(Group::class)
                    ->withPivot('user_role')
                    ->withTimestamps();        
    }

    public function events()
    {
        return $this->belongsToMany(Event::class);
    }

}

migrations for relation are

class CreateEventUserTable extends Migration
{

    public function up()
    {
        Schema::create('event_user', function (Blueprint $table) {
            $table->uuid('event_id');
            $table->uuid('user_id');
            $table->primary(['event_id', 'user_id']);

            $table->foreign('event_id')->references('id')->on('events');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }


    public function down()
    {
        Schema::dropIfExists('event_user');
    }
}

and

class CreateGroupUserTable extends Migration
{

    {
        Schema::create('group_user', function (Blueprint $table) {
            $table->uuid('group_id');
            $table->uuid('user_id');
            $table->string('user_role')->nullable();
            $table->timestamps();
            $table->boolean('owner');
            $table->primary(['group_id', 'user_id']);

            $table->foreign('group_id')->references('id')->on('groups');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('group_user');
    }
}

so I was trying to delete user like this

public function delete($user) 
{
    $user = User::findOrfail('id', $user->id);
    $res = $user->groups()->events()->delete();

    if ($res) {
        return response('Success, user was deleted', 204);
    } else {
        return response()->json(error);
    }
}

but still, I'm receiving

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`event_activities`, CONSTRAINT `event_activities_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: delete from `users` where `id` = someID) in file /home/server/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 664 

I was hoping to do deletion in the manner by relationship in the User model, but I'm still receiving an Integrity error, so what is the proper way of doing this?

copser
  • 2,523
  • 5
  • 38
  • 73

1 Answers1

1

There are 3 ways to achieve this:

  • Using detach

    $user->groups()->events()->detach();
    $user->groups()->detach();
    
  • Utilise the deleting event on related models like in this answer

  • Migrations.

    // in user_roles
    
    $table->integer('group_id');
    $table->foreign('group_id')->references("id")->on("groups")->onDelete("cascade");
    

    This translates into: When group 'id' is deleted on 'groups', delete this row.

    Apply same thing to groups for events.

Edit:

Looking at your migrations, you implemented 3rd solution, but you seem to forget

->onDelete('cascade');

senty
  • 12,385
  • 28
  • 130
  • 260