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,
        ]);
    }
}
相关推荐
专注前端30年2 小时前
【PHP开发与安全防护实战】性能调优手册
android·安全·php
oMcLin3 小时前
如何在 RHEL 7 上优化 Nginx 与 PHP‑FPM 配置,确保高并发 Web 应用的稳定性与响应速度?
前端·nginx·php
IT=>小脑虎6 小时前
PHP零基础衔接进阶知识点【详解版】
开发语言·学习·php
xifangge20257 小时前
PHP 接口跨域调试完整解决方案附源码(从 0 到定位问题)
开发语言·php
ICT董老师8 小时前
通过kubernetes部署nginx + php网站环境
运维·nginx·云原生·容器·kubernetes·php
bleach-8 小时前
buuctf系列解题思路祥讲--[SUCTF 2019]CheckIn1--文件上传以及user.ini的应用
nginx·web安全·网络安全·php
BingoGo10 小时前
免费可商用商业级管理后台 CatchAdmin V5 正式发布 插件化与开发效率的全面提升
vue.js·后端·php
AI 智能服务21 小时前
第6课__本地工具调用(文件操作)
服务器·人工智能·windows·php
松涛和鸣1 天前
49、智能电源箱项目技术栈解析
服务器·c语言·开发语言·http·html·php
晚枫歌F1 天前
io_uring的介绍和实现
开发语言·php