I know about Laravel's accessors and mutators that can adjust attribute values when getting or setting a model. However, this can be done only with existing model attributes. I wonder if there's any way to create a combination of accessor and mutator that would let me set custom attributes for every model item.
Then, when I e.g. retrieve tags with Eloquent:
$tags = Tag::all();
I could access the existing attributes in a loop:
foreach ($tags as $tag) {
echo $tag->id.'<br>';
echo $tag->name.'<br>';
// and ohers
}
but also the custom ones that I set, like $tag->customAttr1
, $tag->customAttr2
.
Is it possible?
Here is example for adding custom attributes to your model. $appends array will add those. While querying your table using eloquent, .. respective getters will be called to set the values.
In the following code snippet 'parent_name' and 'parent_img_url' are custom attributes and getParentNameAttribute and getParentImgUrlAttribute are getters.
One can modify the code of getters as per our need.
class Code extends Eloquent {
protected $table = 'codes';
protected $appends = array('parent_name', 'parent_img_url');
protected $guarded = array();
public static $rules = array();
public function components()
{
return $this->belongsToMany('Component', 'component_codes', 'component_id', 'code_id');
}
public function getParentNameAttribute()
{
$parent = Component::find(50);
return $parent->name_en;
}
public function getParentImgUrlAttribute()
{
$parent = Component::find(50);
return $parent->thumb;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With