Parent model still returns soft deleted child instance

764 views Asked by At

I have a parent model Library which has many Books. Eloquent makes it so easy to define the relationships. I have enabled softdeleting on the book mode using the SoftDeletes trait.

Problem:

When I delete a book instance, the deleted_at attribute on the book instance is set to the current timestamp (as expected).

But when I query all the books that belong to the Library, the result contains all the books, including the ones that were deleted.

I only want to get the books that have not been deleted.

class Library extends Model {
   public function books() {
      return $this->hasMany(Book::class);
   }
}

class Book extends Model {
   use SoftDeletes;
   public function library() {
      return $this->belongsTo(Library::class, 'library_id');
   }
}

$softDeleteBook = Book::find(1);
$softDeleteBook->delete();
$books = Library::find(1)->books;
// $books contains even $softDeleteBook
// I do not want to get $softDeleteBook
1

There are 1 answers

2
Olotin Temitope On

@Elisha-Wigwe Chijioke. Have you added $table->softDeletes(); to your migration file.

Sample model goes like this

<?php 
class Video extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    public function category()
    {
        return $this->belongsTo('LearnCast\Category');
    }
 }
?>

Take a look at a sample migration schema build up

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('videos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
        $table->softDeletes();
    });
}

I hope this helps