KOlm
KOlm

Reputation: 1

Laravel: error with http method using pagination and sorts

I have a livewire component callled products, that allows me to sort, filter and change between pages with paginate, but when I try to change my page and a filter is active, i get the error:

The GET method is not supported for this route. Supported methods: POST.

I have tried to change the route method for

Route::post and Route::any but nothig seems to work

This is my Controller code

<?php

namespace App\Http\Livewire;

use App\Models\Category;
use App\Models\Product;
use Livewire\Component;

class Products extends Component
{
    public $sort = 'id-desc';
    public $category = 'Any';

    public function render()
    {
        $sortarray = explode('-', $this->sort);

        if ($this->category != 'Any') {
            $selectedCategory = Category::where('category', 'like', $this->category)->first();
            $products = Product::where('category_id', '=', $selectedCategory->id)
                ->orderBy($sortarray[0], $sortarray[1])
                ->paginate(12);
        }
        else  $products = Product::orderBy($sortarray[0], $sortarray[1])->paginate(12);

        return view('livewire.products', compact('products', 'categories'));
    }
}

The $sort and $category atributes are my filters, and $sortarray just split the sort attribute

I call the pagination with

@if ($products->hasPages())
    <div class="paginationContainer">{{$products->links('vendor.pagination.default')}}</div>
@endif

And this is my route

Route::get('/Products', ProductController::class)->name('products');

The controller just calls the component

Any information you need, just ask it. Thanks for the help

Upvotes: 0

Views: 67

Answers (1)

Peppermintology
Peppermintology

Reputation: 10210

In order to get pagination working as expected with Livewire, you need to use the WithPagination trait on your Product Component.

class Product extends Component
{
    use WithPagination;

    // everything else
}

You might also want to consider using the protected $queryString property so that Livewire will update the URL query string when properties change.

protected $queryString = [
    'category',
    'sort',
];

Upvotes: 1

Related Questions