Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine accessor and mutator logic to add custom attributes to a model

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?

like image 310
lesssugar Avatar asked Jun 02 '15 10:06

lesssugar


1 Answers

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;
    }

}
like image 84
Ashwini G. Avatar answered Nov 06 '22 14:11

Ashwini G.