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,
        ]);
    }
}
相关推荐
拍客圈8 小时前
内容页底部 采集的同时 隐瞒封面图
服务器·php
tryqaaa_11 小时前
学习日志(二)【linux全部命令,http请求头{有例题},Php语法学习】
linux·学习·http·php·web
Johnstons14 小时前
网络故障定位工具怎么搭配:Wireshark、tcpdump、监控平台各自该在什么时候上场?
数据分析·wireshark·php·es·tcpdump·网络故障定位工具搭配与选型
aq553560014 小时前
Laravel 10.x重磅升级:PHP 8.1+新时代
开发语言·php·laravel
QCzblack15 小时前
php-ser-libs
android·开发语言·php
代龙涛15 小时前
WordPress archive.php 分类与归档页面开发指南
开发语言·后端·php·wordpress
YaBingSec15 小时前
玄机靶场—Apache-druid(CVE-2021-25646) WP
java·开发语言·笔记·安全·php·apache
BingoGo16 小时前
使用 PHP TrueAsync 改造 Laravel 协程异步化的可行路径
php·laravel
aq553560016 小时前
Laravel 6.x新特性全解析
php·laravel
不会编程的崽16 小时前
0CTF piapiapia PHP反序列化+字符串逃逸
安全·web安全·网络安全·php