@nolros
If I understand correctly you want to select your data, and print the collection to json. Why all this bullshit ? :)
In your controller / repository / whatever, get the data
$spaces = $i_dont_know_what_object->spaces()->with(['organization', 'timezone', 'country', 'industry', 'likes', 'activities', 'followers', 'tags'])->get();
Print the collection in order to have json
{!! $spaces !!} // Spaces printed as json.
Then I see you want more control over the displayed data. Option 1 quick, make a custom collection and a method formatting your spaces as json
class SpacesCollection extends Collection {
public function getFormattedAsJsonForMyJavascript()
{
$data = [];
foreach($this as $space)
{
'uuid' => $space->uuid,
'name' => $space->name,
'description' => $space->description,
'organization_name' => $space->organization->name,
'timezone_time' => $space->timezone->time,
'timezone_region' => $space->timezone->region,
'industry_code' => $space->industry->code,
'industry_description' => $space->industry->description,
'country_code' => $space->country->country_code,
'country_citizenship' => $space->country->citizenship,
'likes' => count($space->likes),
'activity' => count($space->activities)
'followers' => count($space->activities),
'tags' => count($space->activities),
'timestamp' => date(Carbon::now()),
}
return json_encode($data);
}
}
Then :
{!! $spaces->getFormattedAsJsonForMyJavascript() !!}
Option 2 way cooler : use fractal and a create a SpacesTransformer. It is cool because it separate the collection from the way it is presented.
Thats it :) No bullshit with an internal array in a collection or a Javascript static call. Everything is in place.
I noticed in all the code you post one of the main problem is you have many methods changing the internal state of the object (like here filling the spaces array). Your objects should have the less state possible and do actions instead. Make them do actions and return things !
Also you put the code at wrong places. Here you put the spaces formatting in the parent collection instead of in the spaces collection.