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,
        ]);
    }
}
相关推荐
2401_834636997 小时前
Nginx 从入门到实战:静态 / 动态站点、PHP 部署与反向代理全解析
运维·nginx·php
绵绵细雨中的乡音16 小时前
监控显示一切正常,可用户根本打不开网站——Blackbox Exporter帮我找到了真相(1)
开发语言·php
右耳朵猫AI17 小时前
PHP周刊2026W22 | WordPress 7.0发布、Laravel 13.10.0、Polyfill 1.38.1、Symfony 8.1
php·laravel·symfony
AC赳赳老秦18 小时前
OpenClaw+AWS 深度应用:自动生成 CloudFormation 模板、批量管理 S3 存储桶
java·python·面试·职场和发展·php·deepseek·openclaw
IpdataCloud19 小时前
信贷审核中如何验证用户地址与IP属地一致性?用IP查询工具实现反欺诈
开发语言·tcp/ip·金融·php·ip
安妮的小熊呢19 小时前
CRMEB BZ v6.0 使用教程:从安装部署到后台基础配置
php·thinkphp·电商系统·crmeb
换个昵称都难19 小时前
WebRTC QoS 实战:从原理到弱网优化
开发语言·php·webrtc
不会写DN20 小时前
通过php 中的Route:: 的写法了解什么是静态类调用
android·java·php
Zhan86112420 小时前
深夜调试法国行情数据API接口的教训:法国CAC40指数WebSocket接入复盘
websocket·网络协议·php
爱装代码的小瓶子20 小时前
muduo库 --socket的封装
服务器·开发语言·php