You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+Orchid如何自定义Notifications返回类并修复分页器属性错误?

问题1:让$request->user()->notifications()返回自定义DatabaseNotification实例

Laravel默认的HasNotifications trait中,notifications()方法关联的是框架自带的Illuminate\Notifications\DatabaseNotification模型。要替换为自定义模型,只需在你的User模型中重写该方法:

  1. 在User模型中引入自定义通知模型
  2. 重写notifications()关联方法,指定自定义模型

示例代码:

use App\Models\orchid\DatabaseNotification;
use Illuminate\Notifications\HasNotifications;

class User extends Authenticatable
{
    use HasNotifications;

    /**
     * 获取用户的通知
     */
    public function notifications()
    {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')
            ->orderBy('created_at', 'desc');
    }
}

重写后,调用$request->user()->notifications()就会返回你自定义的App\Models\orchid\DatabaseNotification实例集合。

问题2:解决分页后访问$notifications->data报错及模型转换问题

首先明确:LengthAwarePaginator实例不存在$data属性,正确获取分页数据的方式是调用$notifications->items()方法,或者直接遍历分页实例(它实现了迭代器接口)。

如果需要确保分页中的每个元素都是自定义模型实例,有两种处理方式:

  • 确保关联返回自定义模型(参考问题1的解决方案),这样分页查询出来的结果本身就是自定义模型实例,无需额外转换。
  • 若因特殊情况需要转换已有分页集合中的模型,可操作分页实例的collection:
$notifications = $request->user()->notifications()->paginate(10);

// 转换集合中的每个元素为自定义模型
$notifications->getCollection()->transform(function ($item) {
    return new App\Models\orchid\DatabaseNotification($item->attributesToArray());
});

注意:不要尝试手动替换LengthAwarePaginator的受保护属性,这不符合Laravel的设计规范,操作集合才是正确的方式。

内容的提问来源于stack exchange,提问作者mstdmstd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:10:31