Eloquent query through many tables

Today this took me a while to figure out, so I'm going to write it down here, maybe it can be helpful for someone.

I'm using Eloquent, the Laravel ORM and I need to perform this query without getting into joins or raw SQL queries.

I need to get the registers from table1 that are related to any register from table5 and filtered by a certain id value for table5.

Table1 and table5 are not directly related, their relationship goes through many tables (table2,table3 and table4), like this:


After struggling for a while this is how I made it:

public function navigation($table5ID){  
    return Table1::whereHas('table2',function($query) use ($table5ID){
        $query->whereHas('table3',function($query2) use ($table5ID){
              $query2->whereHas('table4',function($query3) use ($table5ID){
                $query3->whereHas('table5',function($query4) use ($table5ID){