Ad

Cannot Get Attribute In Laravel Accessor (October CMS)

- 1 answer

I'm currently working on a project with October CMS, and trying to use taglist with relation data. And I'm using custom accessor to get full name from two columns, seems like a very common case.

But I just couldn't get the model's attributes in the accessor.

Here's my code...

class NameOfClass extends Model
{
    /** ALL THE CODE GENERATED BY OCTOBER CMS PLUGIN BUILDER */

    public function getFullNameAttribute()
    {
        return $this->firstname." ".$this->lastname;
    }
}

And call the accessor in field.yml file...

fieldName:
  label: FieldName
  descriptionFrom: description
  type: taglist
  mode: relation
  nameFrom: full_name
  customTags: false

I can see the accessor gets called just fine, since I can get the value by changing the returned value to plain string.

I've been spent a lot of time researching for solution... any idea?

I'm developing with the official octobercms docker image latest version.

Ad

Answer

Its not possible due to internal code. so I suggest do not try to solve it. its not solvable :) try alternative

WHY ??

Because from code taglist is designed in a such way that it will work with TAGS. it will allow to create new tags if there are no selected tag and if tags are existing then it will attache to given record. and this all will work with real attributes.

so its not design to work with virtual attributes.

For more details this is the code how it generates tags

public function getFieldOptions()
{
    $options = $this->formField->options();

    if (!$options && $this->mode === static::MODE_RELATION) {
        $options = RelationBase::noConstraints(function () {
            $query = $this->getRelationObject()->newQuery();

            // Even though "no constraints" is applied, belongsToMany constrains the query
            // by joining its pivot table. Remove all joins from the query.
            $query->getQuery()->getQuery()->joins = [];

            return $query->lists($this->nameFrom); // <==== LOOK HERE
        });
    }

    return $options;
}

You can see this nameFrom is directly passed to query and query/sql do not know about our virtual field so it wont work.

Alternatively you can use RelationController Behaviors
ref: https://octobercms.com/docs/backend/relations#introduction

if any doubt please comment.

Ad
source: stackoverflow.com
Ad