Reputation: 406
Basically my problem is that my models don't inherit the needed attributes from their super class. I already found this question: inherited attributes are null, which addresses the same problem. However the solution did not work for me.
I tried it, but the fillable attributes are just not set. My subclasses don't have access to the attributes.
Maybe I'm doing something wrong?
Extra info (not essential I guess)
My situation is like this: Users (table 'users') can be Advisors (table 'advisors') and/or Customers (table 'customers').
So all the general information about users; first_name, last_name, ... is stored in the users table. Specific information like customer_number or function is stored in the appropriat tables. Both advisors and customers have different relations as they have different roles in the application.
I designed my models so that Advisor and Customer inherit from the super class User:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('email', 'first_name', 'last_name', 'email', 'gender', 'phone_number', 'profile_picture');
protected $hidden = array('password');
protected $guarded = array('id', 'password');
protected $table = 'users';
...
}
And my Advisor class:
class Advisor extends User {
protected $table = 'advisors';
protected $fillable = array('active', 'function', 'description') ;
//this does not work!
public function __construct (array $attributes = array()) {
// the static function getFillableArray() just returns the fillables array
$this->fillable = array_merge ($this->fillable, parent::getFillableArray());
parent::__construct($attributes);
}
...
}
I also tried to call the constructor before setting the fillables, as suggested by: this question. Also did not work.
What did work, was writing accessors in the User super class like this:
// Attribute getters - Inheritence not working
public function getFirstNameAttribute($value)
{
$returnValue = null;
if($value){
$returnValue = $value;
}else{
$returnValue = User::find($this->id)->first_name;
}
return $returnValue;
}
But this is ugly, not efficient and bad for obvious reasons. Is there really no way that I can inherit these attributes? What am I missing?
Thanks in advance
Upvotes: 4
Views: 1135
Reputation: 676
An alternative approach to your problem since you've design a single table inheritance structure in your DB, you could've use Laravel eloquent relationship function explained here: http://laravel.com/docs/eloquent#relationships. That'll allow you to access the attribute of the superclass, example:
//in your Advisor model
public function profile()
{
return $this->belongsTo('User');
}
//to call for advisor's first name
Advisor::find($id)->profile->first_name;
Upvotes: 1