It seems like the issue you're facing is related to Livewire's state management when dealing with query string parameters and navigation. When you navigate to a category and then attempt to paginate or search, the category filter is lost because the state is not properly maintained in the URL.
To fix this, you need to ensure that the category state is preserved in the URL when performing other actions like searching or paginating. Here's how you can modify your Livewire component to handle this:
- Use Livewire's
WithQueryStringtrait to keep track of the query string parameters. - Update the
setCategorymethod to redirect with the category parameter. - Ensure that the pagination links include the current state of the query string parameters.
Here's the updated Livewire component:
namespace App\Livewire;
use App\Models\BlogPost;
use App\Models\BlogCategory;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithQueryString;
class BlogPostList extends Component
{
use WithPagination, WithQueryString;
public $search = '';
public $category = '';
protected $queryString = [
'search' => ['except' => ''],
'category' => ['except' => ''],
];
public function updatingSearch()
{
$this->resetPage();
}
public function updatingCategory()
{
$this->resetPage();
}
public function setCategory($slug)
{
$this->category = $slug;
$this->resetPage();
}
public function clearCategory()
{
$this->category = '';
$this->resetPage();
}
public function blogPosts()
{
$query = BlogPost::published()->orderBy('published_at', 'desc');
if ($this->search) {
$query->where('title', 'like', "%{$this->search}%");
}
if ($this->category) {
$query->whereHas('categories', function ($query) {
$query->where('slug', $this->category);
});
}
return $query->paginate(4);
}
public function blogCategories()
{
return BlogCategory::whereHas('blogPosts', function ($query) {
$query->published();
})->get();
}
public function render()
{
return view('livewire.blog-post-list', [
'blogCategories' => $this->blogCategories(),
'blogPosts' => $this->blogPosts()
]);
}
}
Make sure your pagination links in the Blade template are generated with Livewire's links() method, which should automatically include the current state of the query string:
{{ $blogPosts->links() }}
By using the WithQueryString trait, Livewire will automatically keep track of the search and category parameters in the URL, ensuring that the state is preserved when you paginate or search.
Lastly, ensure that your x-paper-link components are correctly setting the active state based on the current query string. If you're using Alpine.js or another front-end framework, you might need to adjust the logic to reactively update based on the Livewire state.