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,
        ]);
    }
}
相关推荐
用户9272472502196 小时前
PHP+JS+CSS+JSON 单页新闻系统实现方案
php
Ashlee_code9 小时前
什么是Web3?金融解决方案
开发语言·金融·架构·eclipse·web3·区块链·php
Sally璐璐14 小时前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
程序猿阿伟15 小时前
《声音的变形记:Web Audio API的实时特效法则》
开发语言·前端·php
Clownseven16 小时前
Shell 脚本实战指南:内网 ARP 洪泛监控与飞书/邮件自动告警
网络·php·飞书
浪裡遊1 天前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
ejinxian1 天前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
zorro_z1 天前
PHP语法基础篇(九):正则表达式
php
高压锅_12202 天前
思科与华为网络设备命令对比指南:从基础操作到高级配置
服务器·华为·php
SuperherRo2 天前
WEB攻防-文件包含&LFI&RFI&伪协议编码算法&无文件利用&黑白盒
php·文件包含·伪协议·lfi·无文件·黑白盒·rfi