Laravel 9 中 if($collection) 误触发问题的解决方案

千丽大大_8619

千丽大大_8619

2026-05-13

395人浏览

原创

Laravel 9 中 if($collection) 误触发问题的解决方案

在 Laravel 9 中,Eloquent 集合对象(如 $signups)即使为空也会被 PHP 视为“真值”,导致 if($signups) 恒成立;应改用 if(!$signups->isEmpty()) 显式判断空集合,并注意变量作用域(如 $sortorder 需在每个分支中独立初始化)。

在 laravel 9 中,eloquent 集合对象(如 `$signups`)即使为空也会被 php 视为“真值”,导致 `if($signups)` 恒成立;应改用 `if(!$signups->isempty())` 显式判断空集合,并注意变量作用域(如 `$sortorder` 需在每个分支中独立初始化。

Laravel 9 对 PHP 类型判断更为严格,尤其在处理 Eloquent 集合(Illuminate\Database\Eloquent\Collection)时,其底层已不再是简单数组,而是一个对象实例。这意味着传统 PHP 的“空数组为 falsy”逻辑不再直接适用:if($signups) 在 Laravel 9 中始终为 true,哪怕 $signups->count() === 0 或 $signups->isEmpty() === true —— 因为集合对象本身不为 null、false 或空字符串,PHP 将其视为 truthy。

laravel-specialist
laravel-specialist

精通 Laravel 10+,遵循现代 PHP 实践的 Laravel 专家。擅长优雅语法、Eloquent ORM、队列系统及企业级特性...

下载

✅ 正确写法:使用 isEmpty() 显式判断

$signups = $query->get();

// ❌ 错误:空集合仍进入分支(Laravel 9 行为)
// if ($signups) { ... }

// ✅ 正确:显式检查是否为空集合
if (!$signups->isEmpty()) {
    $invoice = new \App\Models\Invoice;
    $invoice->created_by = \Auth::id();
    $invoice->recipient_id = $club->id;
    $invoice->recipient_type = 'App\Models\Club';
    $invoice->sender_id = $sender->id;
    $invoice->sender_type = $type;
    $invoice->sender_name = $sender->name;

    $invoice_nr = \App\Models\Invoice::GenerateInvoiceNumber($type, $sender->id);
    $invoice->invoice_nr = $invoice_nr;
    $invoice->invoice_reference = $sender->id . date('Y') . $invoice_nr;
    $invoice->save();

    $sortorder = 0; // ✅ 必须在此处初始化(作用域限定)

    foreach ($signups as $signup) {
        $sortorder++;
        $invoice->expiration_date = max(
            $invoice->expiration_date ?? null,
            $signup->Competition->signups_closing_date
        );

        $invoice->InvoiceRows()->create([
            'description' => sprintf(
                '%s %s %s (%s)',
                $signup->User->full_name,
                $signup->Competition->name,
                $signup->Competition->date,
                $signup->Competition->championships_id
                    ? $signup->Weaponclass->classname_general
                    : $signup->Weaponclass->classname
            ),
            'quantity' => 1,
            'unit' => _('st'),
            'net_unit_amount' => $signup->registration_fee,
            'vat_percent' => 0,
            'vat_amount' => 0,
            'row_net_amount' => $signup->registration_fee,
            'row_vat_amount' => 0,
            'row_sum_amount' => $signup->registration_fee,
            'sortorder' => $sortorder
        ]);

        $invoice->Signups()->save($signup);
    }

    $invoice->amount = $invoice->InvoiceRows()->sum('row_sum_amount');
    $invoice->expiration_date = max(
        $invoice->expiration_date ?? date('Y-m-d'),
        date('Y-m-d')
    );
    $invoice->save();
    $invoices->push($invoice);
}

⚠️ 同样适用于 $teams 分支

// ✅ 正确:先确保 $teamIds 是有效非空数组,再查询
if (!empty($teamIds) && $teamIds[0] !== '') {
    $query = \App\Models\Team::with('Competition', 'Weapongroup')
        ->whereIn('teams.id', $teamIds)
        ->orderBy('competitions_id')
        ->orderBy('name')
        ->where(function ($q) use ($club, $sender, $type) {
            $q->whereNull('invoices_id');
            $q->where('clubs_id', $club->id);
            $q->whereHas('Competition', function ($cq) use ($sender, $type) {
                $cq->where('invoices_recipient_type', $type);
                $cq->where('invoices_recipient_id', $sender->id);
            });
        });

    $teams = $query->get();

    if (!$teams->isEmpty()) {
        $invoice = new \App\Models\Invoice;
        // ... 其他字段赋值(略)

        $invoice_nr = \App\Models\Invoice::GenerateInvoiceNumber($type, $sender->id);
        $invoice->invoice_nr = $invoice_nr;
        $invoice->invoice_reference = $sender->id . date('Y') . $invoice_nr;
        $invoice->save();

        $sortorder = 0; // ✅ 关键:每个分支必须独立声明 $sortorder!

        foreach ($teams as $team) {
            $sortorder++;
            $invoice->expiration_date = max(
                $invoice->expiration_date ?? null,
                $team->Competition->signups_closing_date
            );

            $invoice->InvoiceRows()->create([
                'description' => sprintf(
                    '%s: %s %s %s (%s)',
                    _('Lag'),
                    $team->name,
                    $team->Competition->name,
                    $team->Competition->date,
                    $team->Weapongroup->name
                ),
                'quantity' => 1,
                'unit' => _('st'),
                'net_unit_amount' => $team->registration_fee,
                'row_sum_amount' => $team->registration_fee,
                'sortorder' => $sortorder
            ]);

            $invoice->Teams()->save($team);
        }

        $invoice->amount = $invoice->InvoiceRows()->sum('row_sum_amount');
        $invoice->expiration_date = max(
            $invoice->expiration_date ?? date('Y-m-d'),
            date('Y-m-d')
        );
        $invoice->save();
        $invoices->push($invoice);
    }
}

? 核心要点总结

  • 永远不要用 if($collection) 判断 Eloquent 集合:它不是数组,是对象,PHP 的 loose comparison 会失效。
  • 统一使用 !$collection->isEmpty():语义清晰、兼容 Laravel 5.3–10+。
  • 变量作用域不可跨分支共享:$sortorder = 0 必须在每个 if 块内显式初始化,否则 Laravel 9 的严格作用域检查会抛出 Undefined variable。
  • 避免 if(!$teamIds[0] == '') 这类易错写法:推荐 !empty($teamIds) && $teamIds[0] !== '' 或更安全的 collect($teamIds)->filter()->isNotEmpty()。
  • 升级提示:Laravel 9 默认启用 PHP 8.0+,对未定义变量、类型隐式转换更敏感,建议开启 strict_types=1 并全面使用 ?Collection 类型提示增强可维护性。

通过以上调整,即可彻底解决“本不该进入的 if 分支被误执行”问题,确保发票仅在真实存在签到或队伍数据时生成。

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

laravel

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

2023.09.01

10904

6

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

2023.10.11

6361

5

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

2023.10.11

2135

5

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

2023.10.23

4008

4

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

2023.10.23

4734

6

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

2023.11.03

3711

9

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

2023.11.09

5317

8

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

2023.11.13

4162

8

sprintf函数用法详解
sprintf函数用法详解

sprintf函数的用法:1、格式化字符串;2、指定输出宽度和精度;3、返回值。更多关于sprintf函数用法详解的内容,大家可以阅读下面的文章。

2023.11.27

12062

4

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
如何安装 Composer
如何安装 Composer

共1课时 | 208人学习

Composer手册
Composer手册

共0课时 | 0人学习