Search code examples
phplaravellaravel-4mass-assignment

how to using just one model for some tables?


I have a website that users can send their product (like car, mobile, computers) and sell it online on my website, maybe something like Ebay and Amazon.

I have ads table that store all public information about one thing using Mass Assignment, and other categories like Mobile, Car and Computers have their own table and will store professional and additional information of that category on it (for example Cars have some additional information like color, fuel type, guaranty, accidents,insurance).

Now as you know I have two tables (ads and ads_mobile), and for all forms I have a controller that is adsController and ads model, form will create dynamically and each form has its own inputs (For Example:Mobile and car has different inputs and fields), and I just send all dynamic forms to adsController@check and then I check what kind of form it is (is that Mobile? is that Car?) and then I want to send this data to model:

//adsController(This is just Example);
 class User extends Eloquent {

protected $fillable_ads = array('field_one', 'field_two', 'field_three');

//And I want to use fillable_mobile_ads too
protected $fillable_mobile_ads = array('field_one', 'field_two', 'field_three');

}

Is this possible?

How should be model and controller?

any suggestion for the structure of my program?


Solution

  • Given your design description, I'd look into a polymorphic relationship. This is useful for when you have multiple models (Mobile, Car, Computer) that share a specific set of information (ads) that is common to all models.

    class Ad extends Eloquent {
        protected $fillable = array('ad_field_one', 'ad_field_two');
    
        public function adable() {
            return $this->morphTo();
        }
    }
    
    class Mobile extends Eloquent {
        protected $fillable = array('mobile_field_one', 'mobile_field_two');
    
        public function ad() {
            return $this->morphOne('Ad', 'adable');
        }
    }
    
    class Car extends Eloquent {
        protected $fillable = array('car_field_one', 'car_field_two');
    
        public function ad() {
            return $this->morphOne('Ad', 'adable');
        }
    }
    
    class Computer extends Eloquent {
        protected $fillable = array('computer_field_one', 'computer_field_two');
    
        public function ad() {
            return $this->morphOne('Ad', 'adable');
        }
    }
    

    To support the above relationships, you would need to add two fields to your ads table: adable_type and adable_id. This can be done in a migration using the statement $table->morphs('adable');

    Documentation on polymorphic relationships can be found here.