James
James

Reputation: 16339

Model accessor attribute returning related model

I have a model called EquipmentProfile which has a relationship with EquipmentProfileType defined like so:

public function equipmentType()
{
    return $this->belongsTo(EquipmentProfileType::class, 'equipment_profile_type_id');
}

I have an accessor defind on EquipmentProfile to enable me to get a specific value from this relationship:

public function getCategoryAttribute()
{
    return $this->equipmentType->name;
}

I am then including category in my $appends array so that it is included when I am returning the model as JSON.

This works perfectly, except in my JSON response I am also getting the whole relationship to EquipmentProfileType too:

//...more fields above
"category": "Brewing",
"equipment_type": {
    "id": 10,
    "name": "Brewing",
    "created_at": null,
    "updated_at": null
}

I only want category to be returned, not the equipment_type object too. If I remove category from my $appends array then equipment_type is not included in the response.

How do I get category to be returned without equipment_type?

Edit

My controller calls a method on a repository:

public function store(EquipmentProfileRequest $request)
{
    $data = $request->except(['api_token']);

    return $this->equipmentProfileRepository->store($data, $request->user());
}

Here is the repository code below:

public function store(array $data, User $user)
{
    if (!array_key_exists('name', $data) || $data['name'] == '') {
        $data['name'] = 'Equipment Profile';
    }

    $data['user_id'] = $user->id;

    return $this->equipmentProfile->create($data);
}

Note

Even using tinker gives me the same result:

Psy Shell v0.9.6 (PHP 7.1.7 — cli) by Justin Hileman
>>> App\Models\EquipmentProfile::first()->toJson()
=> "{... "category":"Brewing","equipment_type":{"id":10,"name":"Brewing","created_at":null,"updated_at":null}}"

Upvotes: 0

Views: 145

Answers (2)

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

Try using this one below:

$result = $this->equipmentProfile->create($data);

return response()->json($result, 200, array(), JSON_PRETTY_PRINT);

That should remove any extra variables and objects.

Upvotes: 0

fubar
fubar

Reputation: 17378

The EquipmentType model is being included in your JSON output, because the relation is automatically loaded when getCategoryAttribute() is called.

To hide it, add the relation name to the hidden array on your model. It will then be filtered out when calling toArray() and toJson().

class EquipmentProfile extends Model
{
    // ...

    protected $hidden = [
        'equipmentType'
    ];

    // ...
}

Upvotes: 1

Related Questions