Question

I have a model Contract that has an accessor for the projects attribute. The attribute is an associative array of "id" => array, but the accessor transforms the array into a collection of Project models:

public function getProjectsAttribute($val)
{
    $projects = array();

    foreach($val as $projId => $projData)
    {
        $proj = new Project($this->roundingPrecision, $projData);
        $proj->_id = $projId;
        $projects[] = $proj;
    }

    return Collection::make($projects);
}

If I get a Contract object, I can call $contract->projects and it works as expected, however, if I return the $contract as JSON (e.g. in a Response), the projects node is empty. I've verified that the accessor is called, but the end JSON does not contain the projects.

So, Response::json($contract) returns a JSON object that includes projects : {}, but Response::json($contract->projects) returns the projects correctly.

Was it helpful?

Solution

This is happening probably because projects is not an attribute of the model and you haven't added 'projects'to the $appends property of your model. http://laravel.com/docs/eloquent#converting-to-arrays-or-json (near the end)

UPDATE:

The problem was happening because of the method attributesToArray not handling instances of ArrayableInterface. A method override has been provided in the comments of this answer, and a relevant patch has been merged to laravel 4.1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top