Merge Laravel Resources into one

So after some digging this doesn't seem to be easily possible. I've decided the easiest way is to just redefine the outputs in the first model and use the mergeWhen() function to only merge when the relationship exists.

return [
    id => $this->id,
    name => $this->name,
    // Since a resource file is an extension
    // we can use all the relationships we have defined.
    $this->mergeWhen($this->Model2()->exists(), function() {
        return [
            // This code is only executed when the relationship exists.
            alternate_name => $this->Model2->alternate_name, 
            child_name => $this->Model2->child_name, 
            parent_name => $this->Model2->parent_name, 
            sibling_name => $this->Model2->sibling_name
        ];
    }
]

Tags:

Php

Laravel