skip to Main Content

Soft deleted records are getting fetched from database.

I have added soft delete to Category model. ‘deleted_at’ column is being set when I soft delete a record. But, when I fetch the result from database using

Category::latest('id')->paginate(20)

it is returning deleted records as well.

My Category model

class Category extends Model
{
    use  SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'is_active',
        'image',
    ];
}

Check query using telescope and it run this.

select * from `categories` order by `id` desc limit 20 offset 0

But it should run

select * from `categories` where `deleted_at` is null order by `id` desc limit 20 offset 0

2

Answers


  1. if you’re seeing soft deleted records when using

    Category::latest('id')->paginate(20),
    

    it’s likely because you need to explicitly tell Eloquent to only fetch non-deleted records. By default, latest() and paginate() do not exclude soft deleted records. like below –

    Category::whereNull('deleted_at')->latest('id')->paginate(20);
    
    Login or Signup to reply.
  2. You should create a migration as well:

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateSupportFacadesSchema;
    
    return new class extends Migration
    {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::table('categories', function (Blueprint $table) {
                $table->softDeletes();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::table('categories', function (Blueprint $table) {
                $table->dropSoftDeletes();
            });
        }
    };
    

    With above, following code will not show deleted categories:

    Category::latest('id')->paginate(20)
    

    by doing above if its not working, then we have only choice left by using following code:

    Category::whereNull('deleted_at')->latest('id')->paginate(20);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search