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,
        ]);
    }
}
相关推荐
真正的醒悟9 小时前
202503-经验之道
服务器·网络·php
wuxuanok11 小时前
ThinkPHP ——安装部署与配置
sql·mysql·nginx·php
霍格沃兹测试学院-小舟畅学14 小时前
性能测试入门:使用 Playwright 测量关键 Web 性能指标
开发语言·前端·php
zorro_z14 小时前
ThinkPHP8学习篇(十三):视图
php
sc.溯琛15 小时前
计算机网络:概论学习1
网络·智能路由器·php
#微爱帮#16 小时前
微爱帮监狱写信寄信小程序PHP高并发优化技术方案
服务器·php·apache
_dindong17 小时前
Linux网络编程:Reactor反应堆模式
linux·服务器·网络·设计模式·php
霸王大陆17 小时前
《零基础学PHP:从入门到实战》教程-模块八:面向对象编程(OOP)入门-5
开发语言·笔记·php·课程设计
霸王大陆18 小时前
《零基础学 PHP:从入门到实战》模块十一:成为 PHP 侦探,精通错误处理与调试实战大全-1
开发语言·笔记·php·课程设计
JaguarJack18 小时前
如何创建和使用 Shell 脚本实现 PHP 部署自动化
后端·php