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,
        ]);
    }
}
相关推荐
Kyln.Wu1 小时前
【python实用小脚本-139】Python 在线图片批量下载器:requests+PIL 一键保存网络图像
数据库·python·php
zorro_z7 小时前
PHP语法高级篇(二):文件处理
php
SuperherRo9 小时前
Web攻防-PHP反序列化&原生内置类&Exception类&SoapClient类&SimpleXMLElement
php·xss·反序列化·exception·ssrf·原生类·soapclient
阿维的博客日记12 小时前
TCP和UDP区别
tcp/ip·udp·php
MZ_ZXD00114 小时前
flask校园学科竞赛管理系统-计算机毕业设计源码12876
java·spring boot·python·spring·django·flask·php
Q_Q196328847516 小时前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
是阿建吖!20 小时前
【Linux | 网络】应用层
linux·网络·php
夏至春来-美美1 天前
php绘图添加水印,文字使用imagick库的操作
php
果子⌂1 天前
Docker高级管理
开发语言·docker·云计算·php
Q_Q5110082851 天前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php