Laravel:使用分页和排序的 http 方法出错

问题描述

我有一个名为 products 的 livewire 组件,它允许我使用 paginate 在页面之间进行排序、过滤和更改,但是当我尝试更改我的页面并且过滤器处于活动状态时,我收到错误消息:

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

我试图改变路由方法

Route::postRoute::any 但似乎没有用

这是我的控制器代码

<?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'));
    }
}

$sort$category 属性是我的过滤器,而 $sortarray 只是拆分了 sort 属性

我用

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

这是我的路线

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

控制器只调用组件

您需要任何信息,尽管问。感谢您的帮助

解决方法

为了让 Livewire 的分页按预期工作,您需要在 Product Component 上使用 WithPagination 特性。

class Product extends Component
{
    use WithPagination;

    // everything else
}

您可能还需要考虑使用 protected $queryString 属性,以便 Livewire 在属性更改时更新 URL 查询字符串。

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