dimanche 22 avril 2018

How to use Laravel Polymorphic Relations when having existing database with lots of user?

I have a User model in my Laravel app. I'm asked to implement a new user type called BusinessUser. However, instead of creating a new model and duplicating lots of code, I thought why not use Laravel's Polymorphic relations.

I can create a userable User model, similar to this and then I can create RegularUser and BusinessUser that inherit from User.

This solution is much cleaner and DRYer. It'd include creating two more tables for regular_users and business_users with respective specific columns while having users to save only basic login info like name, email...etc.

So far so good, BUT what about existing user in the database? The clean solution includes dropping some columns from users and adding them to regular_users, so that users only contains what's common between regular and business users and I can't lose data in the production DB.

This is the User Model - fields that are commented out need to be moved to regular_user:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable();
            //$table->enum('gender', ['male', 'female'])->nullable();
            //$table->date('birthdate')->nullable();
            $table->string('email')->nullable()->unique();
            $table->string('password')->nullable();
            $table->string('mobile_number')->nullable()->unique();
            //$table->integer('country_id')->nullable();
            //$table->integer('city_id')->nullable();
            //$table->integer('role_id')->default(1)->references('id')->on('roles');
            //$table->text('bio')->nullable();
            //$table->enum('privacy', ['public', 'private'])->default('public');
            $table->enum('account_status', ['pending', 'active', 'suspended'])->default('active');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire