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,
        ]);
    }
}
相关推荐
姜太小白13 小时前
【Linux】df -h 卡住问题的通用排查与解决方案总结
linux·运维·php
狗凯之家源码网15 小时前
短剧系统搭建实战:源码功能与商业变现效果全景展示
开发语言·php
连续讨伐17 小时前
php小结
开发语言·php
2601_9657984718 小时前
MTDb Movie & TV Database Script Setup, Caching, and SEO Guide
linux·服务器·数据库·php
小小代码狗20 小时前
PHP 常用函数与变量参考文档
开发语言·安全·php
看昭奚恤哭21 小时前
LWIP TCP滑动窗口为TCP ZeroWindow的解决方法
网络·tcp/ip·php
AC赳赳老秦21 小时前
CSDN 技术社区数据采集:OpenClaw 抓取公开技术热帖,生成领域技术热点周报
java·大数据·前端·数据库·python·php·openclaw
烟漠河洛21 小时前
俄罗斯电商3200亿卢布疯长:跨境支付与多平台订单系统架构解析
mysql·php
wang_xin_8881 天前
PHP函数
开发语言·php
Immortal__y1 天前
php函数
开发语言·php