Hello -
$sites = collect([]);
foreach(Auth::user()->companies as $company) {
$sites->merge($company->sites);
}
return view('site.index', compact('sites'));
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello All,
I have the below code that is trying to get all the sites for the user that belongs to each company:
$site = collect([]);
foreach(Auth::user()->companies as $company)
{
$site = $company->sites->pluck('id');
//dd($site);
}
$sites = Site::findOrFail($site);
//dd($sites);
return view('site.index')
->with(['sites' => $sites]);
when check the first dd I get the below:
Collection {#424 ▼
#items: array:164 [▼
0 => 277
1 => 278
2 => 279
3 => 280
4 => 281
5 => 282
6 => 283
7 => 284
8 => 430
9 => 751
10 => 752
Which is what I would be expecting, a full list of the site id's that the user belongs too, but when I check the last dd I get the below:
Collection {#589 ▼
#items: array:1 [▼
0 => Site {#586 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:16 [▶]
#original: array:16 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
which is only showing a single site, could someone please point out what I am doing wrong? I need a list of sites that the user has access too to show in a view that I have already created:
@foreach ($sites as $site)
<tr>
<td>{{ $site->id }}</td>
<td>{{ $site->sitename }}</td>
<td>{{ $site->spostcode }}</td>
<td>{{ $site->status }}</td>
<td>
<a href="{{ route('users.edit', $site->id) }}" class="btn btn-info pull-left" style="margin-right: 3px;">Reports</a>
<a href="{{ route('sites.show', $site->id) }}" class="btn btn-info pull-left" style="margin-right: 3px;">Information</a>
</td>
</tr>
@endforeach
Thanks in advance.
Hi @IgorBabko,
I have fixed it:
$sites = collect([]);
foreach(Auth::user()->companies as $company)
{
$sites = $sites->merge($company->sites);
}
return view('site.index', compact('sites'));
}
Added the $sites =.
Thanks for all your help.
Please or to participate in this conversation.