In my application I have two columns employable_id
&& employable_type
in almost every table, which are used for storing the information about the user who has created the record.
Something like this:
subscribers: products:
------------------------------------ ------------------------------------
id | employable_id | employable_type id | employable_id | employable_type
------------------------------------ ------------------------------------
1 | 1 | App\Company 1 | 1 | App\Company
2 | 1 | App\Company 2 | 1 | App\Employee
3 | 1 | App\Employee 3 | 3 | App\Employee
4 | 1 | App\Employee 4 | 8 | App\Employee and more...
Subscriber.php
class Subscriber extends Model
{
/**
* Polymorphic relations
*/
public function employable()
{
return $this->morphTo();
}
}
I have created an accessor
to combine polymorphic relationship's columns, which is working fine.
class Subscriber extends Model
{
/**
* Polymorphic relations
*/
public function employable()
{
return $this->morphTo();
}
/**
* Accessor
*/
public function getAddedByAttribute()
{
return $this->employable->name . ' [ ' . $this->employable->designation . ' ]';
}
}
class Product extends Model
{
/**
* Polymorphic relations
*/
public function employable()
{
return $this->morphTo();
}
/**
* Accessor
*/
public function getAddedByAttribute()
{
return $this->employable->name . ' [ ' . $this->employable->designation . ' ]';
}
}
I am trying to make the getAddedByAttribute
method global instead of adding in every model class.
How can I do that..?
you can make a trait and use it in every model need this function