Laravel Livewire 分页问题

场景:

博客的文章列表需要增加分页,代码及报错信息如下:

php 复制代码
<?php

namespace App\Livewire\Components;

use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;
use App\Models\Article as ArticleModel;
use Livewire\WithPagination;

class Article extends Component
{

    use WithPagination;

    public $articles;

    public function mount($category_id = false)
    {
        $this->articles = ArticleModel::query()
            ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
            ->with('category')
            ->when($category_id, function (Builder $query, string $category_id) {
                $query->where('category_id', $category_id);
            })
            ->orderByDesc('id')
            ->paginate(10);
    }

    public function render()
    {

        return view('livewire.components.article', [
            'articles' => $this->articles,
        ]);
    }
}

Property type not supported in Livewire for property:

原因是 livewire 组件类中属性不支持分页对象,所以导致报错

解决方法:

将原有的查询逻辑代码由 mount 转移到 render 方法中。

php 复制代码
<?php

namespace App\Livewire\Components;

use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;
use App\Models\Article as ArticleModel;
use Livewire\WithPagination;

class Article extends Component
{
    use WithPagination;

    public $category_id;

    public function mount($category_id = false)
    {
        $this->category_id = $category_id;
    }

    public function render()
    {
        $category_id = $this->category_id;
        $articles = ArticleModel::query()
            ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
            ->with('category')
            ->when($category_id, function (Builder $query, string $category_id) {
                $query->where('category_id', $category_id);
            })
            ->orderByDesc('id')
            ->paginate(10);
        return view('livewire.components.article', [
            'articles' => $articles,
        ]);
    }
}
相关推荐
Vect__4 小时前
TCP Socket编程详解
网络协议·tcp/ip·php
REDcker4 小时前
TCP 拥塞控制算法详解:CUBIC、BBR 及传统算法
tcp/ip·算法·php
小学导航员6 小时前
VMWARE虚拟机上不了网络
服务器·网络·php
上海合宙LuatOS7 小时前
LuatOS ——fota 升级教程
开发语言·人工智能·单片机·嵌入式硬件·物联网·php·硬件工程
AI量化价值投资入门到精通7 小时前
数据清洗:大数据领域的必备技能
大数据·开发语言·ai·php
小邓睡不饱耶10 小时前
基于Spark GraphX构建用户信任网络:精准定位高价值目标用户
大数据·spark·php
toooooop821 小时前
php BC MATH扩展函数计算精度-第三个参数
开发语言·php
青岑CTF1 天前
攻防世界-Php_rce-胎教版wp
开发语言·安全·web安全·网络安全·php
catchadmin1 天前
Laravel AI SDK 在 Laracon India 2026 首次亮相
人工智能·php·laravel
云游云记1 天前
php 高精度数学扩展 bcmath 知识笔记
笔记·php·bcmath