Reputation: 671
I having problem with pagination, so far I looked at the docs but I can not find in there. I also looked at other post on stack overflow but they don't have the conditions I have in this case. So how can I paginate the if
statement because I get the error
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$threads
because when you paginate you need to get it straight out of the model like this model::paginate()
so how can you do it in this case?
the controller
public function index(Request $request)
{
if($request->has('tags')){
$tag = Tag::find($request->tags)->paginate(10);
$threads = $tag->threads;
} else {
$threads = Thread::paginate(10);
}
return view('thread.index', compact('threads'));
}
so how can you properly paginate $tag = Tag::find($request->tags)->paginate(10);
this?
the blade that generates a link where the controller get the tag
from if that link is clicked
<div class="col-md-3">
<h4>Tags</h4>
<ul class="list-group">
<a href="{{route('thread.index')}}" class="list-group-item">
<span class="badge">14</span>
All Threads
</a>
@foreach($tags as $tag)
<a href="{{route('thread.index',['tags' => $tag->id])}}" class="list-group-item">
<span class="badge">14</span>
{{$tag->name}}
</a>
@endforeach
</ul>
Update
var_dump($request->tags);
in the controller drops string(1) "2"
Upvotes: 0
Views: 2408
Reputation: 5082
You can use the whereHas()
method to add relational conditions (docs).
if ($request->has('tags')){
$threads = Thread::whereHas('tags', function ($query) use ($request) {
$query->whereIn('tags.id', $request->tags);
})->paginate(10);
} else {
$threads = Thread::paginate(10);
}
In this example you need to change the third line with the whereIn
method to your correct needs.
Upvotes: 3