because with a db join, you are no longer using eloquent and dont have nested datasets
Use eloquent to load those related models, and use eager loading to avoid n+1 issues (You should google this)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have set up all the relationships for my tables in each of the Models.
I can get the required information in my views if I use:
// In ProjectController
$projects = Project::all();
Then in my view, I can call the following and it all works as expected:
// In projects View
@foreach($projects as $project)
<tr>
<td>{{ $project->number }}</td>
<th>{{ $project->subSector->sector->segment->name }}</th>
<td>{{ $project->subSector->sector->name }}</td>
<td>{{ $project->subSector->name }}</td>
<td>{{ $project->name }}</td>
<td>
<a href="{{ url('clients', $project->client->id) }}">{{ $project->client->name }}</a>
</td>
<td>{{ $project->city->state->country->name }}</td>
<td>{{ $project->city->name }}</td>
<td>{{ $project->locale->name }}</td>
</tr>
@endforeach
However, when using this query in my Controller to return filter results:
// In GovernmentController
$government = DB::table('countries')
->join('states', 'countries.id', '=', 'states.country_id')
->join('cities', 'states.id', '=', 'cities.state_id')
->join('projects', 'cities.id', '=', 'projects.city_id')
->join('sub_sectors', 'projects.sub_sector_id', 'sub_sectors.id')
->join('sectors','sub_sectors.sector_id','sectors.id')
->where([['sectors.name','=','Government'],['countries.name', '=', 'Australia']])
->select('projects.*')
->get();
This returns all the projects as expected:
How do I now display all of the project info as follows in the view to return related data like sub-sector?
// In Government view
@foreach($government as $project)
<tr>
<td>{{ $project->id }}</td>
<td>{{ $project->name }}</td>
<td>{{ $project->subSector->name }}</td> // Get Error
</tr>
@endforeach
I get this error
"Undefined property: stdClass::$subSector "
Thanks in advance
Please or to participate in this conversation.