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

Laravel递归Collection宏报错:Call to a member function map() on null

问题:调用Collection宏recursive后出现Call to a member function map() on null错误

我在Laravel项目中为Meilisearch添加过滤功能时,在App\Providers\AppServiceProvider.php定义了名为recursive的Collection宏,但调用该宏处理过滤逻辑时触发Error:Call to a member function map() on null错误。

宏定义代码

// App\Providers\AppServiceProvider.php
public function boot(): void
{
    Collection::macro('recursive', function () {
        $this->map(function ($value) {
            if (is_null($value)) return;
            if (is_array($value) || is_object($value)) {
                return collect($value)->recursive();
            }

            return $value;

        });
    });
}

调用代码及上下文

// dd($this->queryFilters)输出:
/*
array:2 [▼ // app\Http\Livewire\ProductBrowser.php:26
  "color" => []
  "size" => []
]
*/

$filters = collect($this->queryFilters)
    ->filter(fn ($filter) => !empty($filter))
    ->recursive()
    ->map(function ($value, $key) {
        return $value->map(fn ($value) => $key . ' = "' . $value . '"');
    })
    ->flatten()
    ->join('AND');
    
dd($filters);

问题原因

错误根源在于recursive宏的定义:该宏没有返回map操作后的Collection实例。Laravel的Collection依赖链式调用,所有操作方法都需要返回集合对象,否则会返回null,导致后续调用map时触发错误。

修复方案

修改recursive宏,确保返回map处理后的集合:

// App\Providers\AppServiceProvider.php
public function boot(): void
{
    Collection::macro('recursive', function () {
        // 关键:返回map操作后的集合实例
        return $this->map(function ($value) {
            if (is_null($value)) return null; // 明确返回null,避免隐式返回
            if (is_array($value) || is_object($value)) {
                return collect($value)->recursive();
            }

            return $value;
        });
    });
}

额外优化提示

  1. 原代码中if (is_null($value)) return;会隐式返回null,改为return null让逻辑更清晰可读。
  2. 结合你的过滤场景,filter(fn ($filter) => !empty($filter))已经过滤掉了空数组,因此调用recursive后剩余的都是非空集合/数组,后续map不会再遇到空值问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:53