Bas Bas - 1 month ago 11
JSON Question

Laravel 5 Eloquent 2 tables with pivot to json

I have 3 tables, naws/facility_naw(pivot table)/facilities.
If make a foreach and another foreach with facilities then it works fine.
Now i want the data to be accessable as api and i want to return all to a json.
So i made a new controller ApiController.

@foreach( $naws as $naw )
@foreach( $naw->facilities )
etc
etc
@end
@endforeach


How can i achieve that?

Tables

Answer

Try this:

 $result = [];

 foreach( $naws as $naw )
 foreach( $naw->facilities )
    $result[] = etc;
 endforeach;
endforeach

return $result;
Comments