mikelovelyuk
mikelovelyuk

Reputation: 4152

Laravel call all attributes at once

How can I call all of my models attributes including the ones defined as accessors/mutators?

At the moment I am creating accessors/mutators like;

public function setSatisfiedWithQualityOfCourseAttribute($value)
{
    $this->attributes['group_answers']['satisfied_with_quality_of_course'] = $value;
}

public function getSatisfiedWithQualityOfCourseAttribute()
{
    if (isset($this->group_answers['satisfied_with_quality_of_course'])) {
        return $this->group_answers['satisfied_with_quality_of_course'];
    }

    return null;
}

And I can call them from my controller with something like $response->satisfied_with_quality_of_course but I need to be able to return all of them without explicitly calling them one at a time. Can I do that?

I need to call all "real" attributes and all "accessors".

Upvotes: 0

Views: 339

Answers (1)

jszobody
jszobody

Reputation: 28911

You can use $response->attributesToArray() to get an array of all attributes, including your custom accessors.

You can use $response->toArray() to get loaded relationships as well, with their attributes.

If your custom accessors define new pseudo attributes (as opposed to overwriting existing database columns) you should also add them to the $appends array.

protected $appends = ['satisfied_with_quality_of_course'];

Upvotes: 1

Related Questions