samedi 2 juin 2018

Delete all posts related to a user in laravel

this is my posts table

   public function up()
        {
            Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('user_id');
                $table->integer('category_id')->unsigned()->index();
                $table->integer('photo_id')->default(0)->unsigned()->index();
                $table->string('title');
                $table->text('body');
                $table->timestamps();

                $table->foreign('user_id')
                    ->references('id')->on('users')
                    ->onDelete('cascade');


            });
        }

this is my users table

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('role_id')->index()->unsigned()->nullable();
            $table->integer('photo_id')->index()->default(0);
            $table->boolean('is_active')->default(0);
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

these are the relations

 public function posts() {
        return $this->hasMany('App\Post');
    }

public function user() {
        return $this->belongsTo('App\User');
    }

I am trying to delete all the posts related to a user when I delete a user. For that, I am using foreign reference constraint in posts table as shown above But it is not working when I delete the user. The posts are still there. I dont know what I am doing wrong



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire