Thelonias
Thelonias

Reputation: 2935

Prevent both relationship object AND relation id from being returned with parent model

I have a model DefectReport:

class DefectReport extends Model
{
    public function site()
    {
        return $this->hasOne(Site::class, 'id', 'site_id');
    }

    public function processCode()
    {
        return $this->hasOne(ProcessCode::class, 'id', 'process_code_id');
    }
}

Those 2 "hasOne" models do not have the inverse "belongsTo" defined in them. This is because those tables (sites and process_codes) have no idea what a defect report is.

When I retrieve an instance of DefectReport from the database, I get the "id" columns of the relationships as well as the relationship objects. Is there any way to get JUST the relationship object?

For example, when I call:

return \App\DefectReport::with(['site', 'processCode'])->findOrFail(1);

I get the following JSON:

{
    "id":1,
    "site_id":1,
    "process_code_id":1,
    ...other fields...
    "created_at":"2015-07-17 19:51:45",
    "updated_at":"2015-07-17 19:51:45",
    "site": { 
        "id":1,
        "location_code":"1",
        "location_desc":"test",
        "created_at":"2015-07-17 19:51:45",
        "updated_at":"2015-07-17 19:51:45"
    },
    "process_code": {
        "id":1,
        "code":"999",
        "description":"some process code",
        "created_at":"2015-07-17 19:51:45",
        "updated_at":"2015-07-17 19:51:45"
    }
}

Notice that both "site_id" and "site" are there? How can I prevent this?

Upvotes: 1

Views: 292

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

In your DefectReport model add:

protected $hidden = array('site_id', 'process_code_id');

$hidden attribute is checked by Eloquent to identify any attributes that should be not returned when Object is serialized.

Upvotes: 2

Related Questions