delete test data in laravel migration script

user269867 picture user269867 · Jan 8, 2016 · Viewed 10.5k times · Source

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','[email protected]')->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!

Answer

Dan Johnson picture Dan Johnson · Jan 8, 2016

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
        ]);

    }