php - laravel - Create a new migration table with data from existing -


i have users table 2 types 'student' or 'faculty' in type column. create 2 different tables user table faculty , students...

i thought of creating 2 models faculty , students can't think ahead of on how populate tables these models.

<?php  use illuminate\database\schema\blueprint; use illuminate\database\migrations\migration;  class createuserstable extends migration {  /**  * run migrations.  *  * @return void  */ public function up() {     schema::create('users', function(blueprint $table)     {         $table->increments('id');         $table->string('name');         $table->string('identif')->unique();         $table->string('type');         $table->string('email')->unique();         $table->string('password', 60);         $table->remembertoken();         $table->timestamps();          //add primary key      }); }  /**  * reverse migrations.  *  * @return void  */ public function down() {     schema::drop('users'); }     } 

the easiest way run raw query , copy data users table other 2 tables, if you're using mysql sth following work:

db::statement("insert students (name, identif, email, password) select (name, identif, email, password) users type = ?", array('student')); 

other databases should offer similar feature.

the above ok if not need eloquent model logic being run records. otherwise fetch user objects, create new student or faculty objects , save new objects:

users::all()->map(function($user) {   if ($user->type == 'student') {     student::create($user->toarray());   } else {     faculty::create($user->toarray());   } }); 

if want new user of faculty object created every time users object created, can use eloquent model events:

//user.php protected static function boot() {   parent::boot();    static::created(function($user) {     if ($user->type == 'student') {       student::create($user->toarray());     } else {       faculty::create($user->toarray());     }   }); } 

Comments