Search code examples
jsoneloquentlaravel-5.3

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


Solution

  • Try this:

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