I
I
Ivan2021-08-03 17:02:31
Laravel
Ivan, 2021-08-03 17:02:31

How to add additional fields to the model through mutators?

Hello. It is necessary to make sure that additional fields are added at the output to the user model, while they are added to a separate collection, not directly to the model. I'm trying to do it with mutators.
In the model:

protected $appends = ['additional'];

public function getAdditionalAttribute()
    {
        return collect();
    }

public function getSomeOptionAttribute()
    {
        //some code
        
        return $this->additional['some_option'] = true;
    }


Then I call this mutator in the controller on the user
$user->append('some_option');

object. As a result, this some_option gets into the user model itself, and not the additional collection in it.
How to make it so that it gets into this collection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-08-03
@Djonson86

public function getAdditionalAttribute(): Collection
{
    return collect([
        'some_option' => true,
   ]);
}

$user->append('additional');
(and remove $appends from the model, since you explicitly call it)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question