Ad

Getting All Attributes For Nested Relationships In Laravel In One JSON

- 1 answer

I am trying to get all attributes in one JSON.

Eg: Consider I have a table "place" with "id","name","description" as attributes. Now, I have another table "region" with "id","name","place_id","description" as attributes(or) schema. There is one to many relationship between place and region.

And now,I define another table "street" with "id","name","region_id" as its schema. There is again One to Many relationship between "region" and "street".

I want to get all details which comes in one place.If there is some place "1,banglore,garden city" and there are two regions with that place_id as "{"1,r.t.nagar,1,region in banglore"},{"2,ashok nagar,1,region in banglore"}".Here "1" is foreign key referring id of "banglore's id(1)".

Now,similarly if each region has 3 streets in street table.I want to get all the values in one JSON. I know that we can get this with foreach .But,i want an efficient solution to get all nested relationship to my Place model from Region,Street in JSON.

Thanks.

Ad

Answer

You first need to define one to many relations like:

 class Places extends Eloquent{
 ....
    public function regions()
    {
        return $this->hasMany('App\Region');
    }
 ...
 }

And the same to streets:

 class Regions extends Eloquent{
 ....
 public function streets()
    {
        return $this->hasMany('App\Street');
    }
....
}

Note that I have assumed that your models stay within App folder and have corresponding namespaces. After that you can get you model like:

Place::with('regions.streets')->get();

Which will automatically nest all relations and cast to JSON if you send a json response.

Ad
source: stackoverflow.com
Ad