dollar dollar - 2 years ago 156
SQL Question

Access all data from multiple Linked Tables in Laravel 5.2

enter image description here

Now In all the 4 models i have provided relations as


When I tried to access a particular city from the table and it's associated state using below code it's working fine.


Now at the same time I also want to access the associated country name for the state. I tried doing this:


This gives me an error message, I know this way it wont work because city and country are not related to each other directly, but I need to access data like this, if I access a specific city then I want it's state as well as it's country in the result.

Answer Source

You can use dot notation to access nested relationships. To quote the Laravel Documentation.

To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

$books = App\Book::with('author.contacts')->get();

In your case, this would look something like:

 $citydetails = City_table::with('states.countries')->find($id);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download