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,
        ]);
    }
}
相关推荐
James. 常德 student44 分钟前
网络安全知识点
安全·web安全·php
玉笥寻珍3 小时前
筑牢信息安全防线:涉密计算机与互联网隔离的理论实践与风险防控
开发语言·计算机网络·安全·计算机外设·php·安全架构·安全性测试
uwvwko4 小时前
BUUCTF——web刷题第一页题解
android·前端·数据库·php·web·ctf
lsswear4 小时前
php fiber 应用
开发语言·php
yyywoaini~4 小时前
序列化和反序列化hadoop实现
hadoop·eclipse·php
kp0000010 小时前
PHP弱类型安全漏洞解析与防范指南
android·开发语言·安全·web安全·php·漏洞
Q_Q196328847513 小时前
python的漫画网站管理系统
开发语言·spring boot·python·django·flask·node.js·php
SRC_BLUE_1716 小时前
VulnHub | Breach - 1
开发语言·php·dreamweaver
jingyu飞鸟1 天前
Centos7系统(最小化安装)安装zabbix7版本详细文章、nginx源代码配置、php源代码、mysql-yum安装
开发语言·php
Q_Q19632884751 天前
python的家教课程管理系统
开发语言·spring boot·python·django·flask·node.js·php