9

I am trying to clean the test data from my production tables. In simple environment I can write a script to clean the test data but I wonder how can I do the same in laravel migration script

I have a test user on production and want to clean all related records generated in the database.In a seed file I can fetch student id based on email address and then remove courses and other info based on the id?. I don't know if it sounds like a laravel way of doing things!

studentId = 101

He is enrolled to three courses He has attendance records He has communication records

Now I want to fetch student id based on his emailId then want to delete records from courses, attendance, communication table and finally delete id from student table

I am doing

$sdetail = student::where('email','some@test.com')->first();
echo "you are checking fir: ".$sdetail ->id;
$classes= class::where('studentId',"$sdetail->id")->get();
foreach($classes as $class)
{
    echo $class->name;   //print only one record I have three rec!
    DB::table('courses')->where("id",$class->id)->delete();
}

any idea fix this!

user269867
  • 3,266
  • 9
  • 45
  • 65

4 Answers4

7

You can run model functions within a migration - you just need to include the model at the top.

use App\ModelName

class RemoveTestData extends Migration {

    public function up(){

        ModelName::where('id', $ID)->first()->delete();

    }

    public function down(){

        ModelName::create([
            //Test Data
        ]);

    }
Dan Johnson
  • 1,480
  • 17
  • 36
4
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

use App\Models\settings;

class ChangeCreateSettingsInsert extends Migration
{
  public function up()
  {
    settings::create([
        "product_id" => 1           
    ]);
  }

  public function down()
  {
    settings::where('product_id',1)->delete();
  }
}
YoJey Thilipan
  • 617
  • 8
  • 10
1

You can use the truncate() function in a migration to remove all rows and reset any auto increment fields.

Schema::table('table_name', function($table)
{
    $table->truncate();
});

https://laravel.com/docs/5.1/queries#deletes

Dan Johnson
  • 1,480
  • 17
  • 36
1

I just bumped into the same exact issue today and I find another way to do it when you hydrate your database:

// Include the model in your file use App\Models\ModelName;

public function down()
{
    ModelName::query()->delete();

}

the query() makes the connection with you DB and allows you to delete your datas

I hope this helps as well :)

Rapkalin
  • 54
  • 5