Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete test data in laravel migration script

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!

like image 930
user269867 Avatar asked Jan 08 '16 20:01

user269867


2 Answers

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

    }
like image 153
Dan Johnson Avatar answered Oct 02 '22 21:10

Dan Johnson


<?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();
  }
}
like image 33
YoJey Thilipan Avatar answered Oct 02 '22 21:10

YoJey Thilipan