2

I am using Laravel 5.2.

I have 3 tables: book, user and book_user (the pivot table).

I want to use soft deletes on my pivot table. When I attach a book to a user, the relationship is inserted into the book_user table. However when I detach this relationship, the record in the pivot table is deleted even though I added use SoftDeletes to the pivot table model.

How can I implement soft deletes for the records in my pivot table when I attach or detach?

1 Answer 1

4

I didn't try it using soft delete with pivot table but you're saying that it doesn't work.

Just an idea, maybe you can use sync instead of detach like this;

Before that you need to add deleted_at column to book_user table as DATETIME instead of TIMESTAMP. Because new version of MYSQL doesn't support NULL for TIMESTAMP type.

Soft Deleting

$user->books()->sync(array(1 => array('deleted_at' => DB::raw('NOW()'))));

Getting

Also you can put a constraint on the Eager Load:

public function books()
{
    return $this
    ->hasMany('Book')
    ->whereNull('book_user.deleted_at');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.