Потому что когда вы ->get()
или ->all()
$category
становитесь коллекцией из Category
, а не Category
@if(request()->segment(2) == 'all')
@php
foreach($category as $cat) {
$campaigns = $cat->users()->orderBy('id', 'desc')->paginate(20);
}
@endphp
@else
@php
$campaigns = $category->users()->orderBy('id', 'desc')->paginate(20);
@endphp
@endif
@if($campaigns->count() > 0)
// some code here
@endif
Edit;
Как вы и спросили Но почему я получаю 0 в качестве результата ниже? Часть ниже перезапишет $campaigns
, так как вы находитесь в foreach
foreach($category as $cat) {
$campaigns = $cat->users()->orderBy('id', 'desc')->paginate(20);
}
Можетa предложить вам что-то другое
public function singleCategory($id){
// Eager loading the users before will increase the performance, by performing one single query instead of repeting the query in a loop
$query = Category::with(['users' => function($query) {
$query->orderBy('id', 'desc')->paginate(20);
}])
if($id == 'all') {
$categories = $query->get();
} else {
// findOrFail() will throw a 404 when the ID doesn't not exists
// [$id] is an array to return a Collection of Category
$categories = $query->findOrFail([$id]);
}
return view('campaigns_by_category', compact('categories'));
}
Тогда в вашем клинке вам не нужно знать, есть ли у вас одна или несколько категорий.
@foreach($categories as $category)
{{-- "In my knowledge we can't alias with eager loading, but you can still make a relationshion campaigns instead of users" --}}
{{ $category->users->count() }}
{{-- "forelse is like a foreach but perform a `else` when users are empty" --}}
@forelse($category->users as $campaign)
{{ $campaign }}
@empty
No campaigns for {{ $category }}
@endforelse
@foreach