简体   繁体   中英

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');
    }

Delete code of the user

public function destroy($id)
    {
        $user = User::findOrFail($id);

        if($user->photo_id !== 0) {
            unlink(public_path() . $user->photo->path);
        }


        $user->delete();

        Session::flash('deleted_user', 'The user has been deleted.');

        return redirect('/admin/users');
    }

Delete code of the post

public function destroy($id)
    {
        $post = Post::findOrFail($id);

        if($post->photo_id !== 0) {
            unlink(public_path() . $post->photo->path);
        }


        $post->delete();

        return redirect('/admin/posts');

    }

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

This problem occurs most probably because the default table engine in your MySQL instance is set to MyISAM which doesn't support foreign keys. Trying to work with foreign keys on a MyISAM table would definitely not be a bug in Laravel. Although it would be nice if the Schema Builder could automatically set the engine to InnoDB if foreign keys are used.

so, use this line in your schema

$table->engine = 'InnoDB';

or alter the table with

ALTER TABLE table_name ENGINE=InnoDB;

May be help you.

Create you custom method like function destroyAllByUser()

and put the code like

DB::table('posts')->where('user_id', '=', 1)->delete();

I hope it may help

Delete user;

public function destroy($id)
{
    $user = User::findOrFail($id);

    if($user->photo_id !== 0) {
        unlink(public_path() . $user->photo->path);
    }

    $user->posts->delete();

    $user->delete();

    Session::flash('deleted_user', 'The user has been deleted.');

    return redirect('/admin/users');
}

A alternative way to solve that is to configure database.php file under laravel-project\\config folder to work on InnoDB engine.

'mysql' => [
   ...

   'engine' => 'InnoDB'
 ]

Now you don't need to worry when you using foreign keys... REMEMBER - If you didn't configured this before you create your tables you should remigrate again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM